Style Guide Flashcards

1
Q

Which of these is correct:
1. if (n < 0) {alert(Power ${n} is not supported);}

  1. if (n < 0)
    alert(Power ${n} is not supported);

3.
if (n < 0) alert(Power ${n} is not supported);

4.
if (n < 0) {
alert(Power ${n} is not supported);
}

A

They all work but use:

  1. for short statements
  2. for most cases
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are some tricks to keep line lengths down under 80-120 characters?
(2 things)

A
  • use backticks for multiple lineslet str = `
    ECMA International’s TC39 is a group of JavaScript developers,
    implementers, academics, and more, collaborating with the community
    to maintain and evolve the definition of JavaScript.
    `;
    Regular quotation marks assume a ; on new line
- put conditionals on new lines in if statements
if (
  (id === 123) &&
  (moonPhase === 'Waning Gibbous') &&
  (zodiacSign === 'Libra')
) {
  letTheSorceryBegin();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When do you add a vertical space between code lines? (1 main principal??)
Give examples within a single function (3 points)

A
Even a single function can often be divided into logical blocks. 
 - the initialization of variables
- the main loop
- returning the result 
should be split vertically
function por() {
  let result = 1;

for () {
}

let x =
let y =

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you avoid nesting if/else statements in a function?

A

Use return to just escape the function. so:
if this, do this and return
If this, do this and return
Rather than
If, if else, etc.

Instead of:
function pow(x, n) {
  if (n < 0) {
    alert("Negative 'n' not supported");
  } else {
    let result = 1;
    for (let i = 0; i < n; i++) {
      result *= x;
    }
return result;   } }
do:
function pow(x, n) {
  if (n < 0) {
    alert("Negative 'n' not supported");
    return;
  }

let result = 1;

  for (let i = 0; i < n; i++) {
    result *= x;
  }

return result;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of these 3 are preferred?

  • functions declared, then used
  • functions used, then declared
  • functions declared right before their first use

Why?

A

Functions used, then declared

This way the functions are all at the bottom and, if the functions are named well, the user may not need to read functions at all to understand the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Basics of JS Case style guide

Style Guide:

constant variables (known and unknown prior to page load)

functions and non-constant variables

constructor functions

A

SCREAMING_SNAKE_CASE- for constants that are known (pi)
but camelCase for unknown constants.- const pageLoadTime;
It’s a constant, but not known prior to page load.

camelCase- for identifier names (variables and functions)

PascalCase for constructors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Tools that can automatically check the style of your code and make improving suggestions.

A

Linter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to avoid nesting if/else statements in a loop.

A
Instead of:
for (let i = 0; i < 10; i++) {

if (i % 2) {
alert( i );
}

}

Do:
for (let i = 0; i < 10; i++) {

if (i % 2 == 0) continue;

alert(i); // 1, then 3, 5, 7, 9
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What do you do if your code needs comments?

A

If the code NEEDS comments, then maybe change the code to be more readable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How would you change this to make the code more readable:

function showPrimes(n) {
  nextPrime:
  for (let i = 2; i < n; i++) {     //iterates over number up to input number
    for (let j = 2; j < i; j++) {
      if (i % j == 0) continue nextPrime;   //checks if prime
    }
alert(i);   } }
A

Create another function to handle as much as possible:

function showPrimes(n) {

  for (let i = 2; i < n; i++) {
    if (!isPrime(i)) continue;
alert(i);   } }

Then have another funcion: isPrime()

function isPrime(input) {
      for (let i = 0; i < input; i++) {
          if prime continue (input % i == 0)
          else return false
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How would you change this to make the code more readable:

// here we add whiskey
for(let i = 0; i < 10; i++) {
  let drop = getWhiskey();
  smell(drop);
  add(drop, glass);
}
// here we add juice
for(let t = 0; t < 3; t++) {
  let tomato = getTomato();
  examine(tomato);
  let juice = press(tomato);
  add(juice, glass);
}

// …

A

Split each task into functions. Name the functions something understandable:

addWhiskey(glass);
addJuice(glass);

function addWhiskey(container) {
  for(let i = 0; i < 10; i++) {
    let drop = getWhiskey();
    //...
  }
}
function addJuice(container) {
  for(let t = 0; t < 3; t++) {
    let tomato = getTomato();
    //...
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

If explanatory comments are bad, what are comments for?
(1 reason for functions
3 reason for overall
)

A
- Document function parameters and usage
For example:
/**
 * Returns x raised to the n-th power.
 *
 * @param {number} x The number to raise.
 * @param {number} n The power, must be a natural number.
 * @return {number} x raised to the n-th power.
 */
function pow(x, n) {
  ...
}
  • Provide birds-eye view of the code (UML)
  • dates and authorship
  • explain WHY the code was chosen for the task. Maybe you did it a less obvious way but it was for a specific reason.
    Like in law: the law that pirating software is bad is one thing, but provide an argument so future you and future generations can understand whether they need to change it or not.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does UML stand for? Briefly what is it?

A

Unified Modeling Language

Diagrams to visualize system or database
https://www.youtube.com/watch?v=WnMQ8HlmeXc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Shorter code is better code

T or F

A

False

Readability and loading speed are the main goals

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

You should avoid using abbreviations and single letters for variable names
T or F

A

True

Readability is more important than variable shortness. You can press tab to get the variable name faster anyway

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

It’s bad to name variables vaguely like: data, value

T or F

A

True

17
Q

It’s OK to reuse variable names as long as you’re sure it’s not going to be used again
T or F

A

False

It works, but it’s not super readable

18
Q

You can make variables like this _apple
where the underscore has special meaning to you
T or F

A

False

Just follow regular rules

19
Q

Never declare a variable inside a function if that same variable name is used outside
(even if the scope works fine)
T or F

A

True

For readability just declare a new variable

20
Q
If the code reads :
ifFunction()
checkPermission()
isReady()
findTags()
validateEmail()
You should not have them perform side effects. They should return what they obviously should (boolean, tags etc)
T or F
A

True

Makes it more readable and useful. You don’t want people to have to read documentation to understand your code.

21
Q

Should there be a space between the function declaration and the first or last line of code in the function block?

Like this:
function pow(x, n) {

let result = 1;

return result + 2;

}

A

first
no

last
no

function pow(x, n) {
  let result = 1;

return result + 2;
}

22
Q
Should you add spaces in between { and } like this:
let anObject = { first: 'entry' }
or not:
let anObject = {first: 'entry'}
A

Don’t have spaces

or do it like this:
let anObject = {
  first: 'entry';
}
23
Q

Which of these is preferred and why?

let name = getNameFromUser();
if (name) { console.log(`Hi ${name}`);
  } else { console.log("you must enter your name!");
}

OR

let name = getNameFromUser();
if (name === "") {
  console.log("you must enter your name!");
} else { console.log(`Hi ${name}`); }
A

The second one is more clear as to what’s going on. While both work, the first might be mistaken for a mistake.

24
Q
let a = 1;
let b = 2;

let c = 3 - (a = b + 1);

Evaluate:

a

c

A

3

0

(but don’t do it)

25
Q

How do you name a construction function?

A

PascalCase

26
Q

Which of these is correct for a nested call

console. log(pow(x, n));
console. log( pow(x, n) );

A

console.log( pow(x, n) );

27
Q

Where should the comment be located in the code? Before, same line or after?)

A

before

28
Q

You should always use strict equality

t or f

A

true

29
Q

When should you use the conditional operator (?) over a series of if/else statements?

A
javascript.info says to use conditional operator tertiary syntax when choosing a value to assign to a variable.
like this:
let message = (age < 3) ? 'Hi, baby!' :
(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';

A bit subjective:
An if/else statement emphasises the branching first and what’s to be done is secondary, while a ternary operator emphasises what’s to be done over the selection of the values to do it with.

If/else can do multiple statements per conditional statement

Tertiary operator is a statement and faster

Tertiary operator is awkward to nest

30
Q

Proper object formatting? (note the spaces)
let anObject = {
one : 1
}

let anObject = {
  one: 1
}
let anObject = {
  one:1
}
A
let anObject = {
  one: 1
}
31
Q

When putting the same line of code on two lines, how many spaces should there be?

A

2 tabs worth

32
Q

Rule of thumb for comments

A

Write code as if they don’t exist.
What’s left after, is what needs to be commented

Code tells you how, Comments tell why