Javascript day 4
Variables
let
can be reassigned later on.
let sum = 0;
sum += 1;
// or
let language = "C++";
language = "JavaScript";
const
cannot be reassigned. We can still change elements inside an array or object.
let or const
Jad encourages always starting with const
. If we need to reassign the variable, then switch to let
.
The benefit of using const
is that once a variable is an array, it will always be an array. We can confidently use array methods on that variable.
Conditions
Here's the blueprint:
if (condition) {
// do something
}
More examples with else if and else:
const grade = 15;
if (grade >= 10) {
console.log("Passing");
} else if (grade === 10) {
console.log("Passing on the limit");
} else {
console.log("Failing");
}
Always use triple equals (===
) when comparing two values in JS. It only returns true if both sides are the same data type and have the same value. Double equals will try to convert both values into the same data type, which we want to avoid.
Advanced if
We can drop else
if possible.
function canVote(age) {
if (age >= 18) {
return true;
}
return false;
}
Returning booleans
Whenever we're returning a boolean, we can make it less redundant.
function isPassing(grade) {
if (grade >= 10) {
return true;
} else {
return false;
}
}
isPassing(12);
// we can refactor it like this:
function isPassing(grade) {
return grade >= 10;
}
Even & Odd
The division remainder of a number divided by two is either 0 or 1. This helps us determine whether the number is even or odd.
function evenOrOdd(number) {
if (number % 2 === 0) {
return "even";
}
return "odd";
}
The ternary operator
We can refactor the example above as follows:
function evenOrOdd(number) {
return (number % 2 === 0) ? "even" : "odd";
}
// the ternary operator has the following syntax:
condition ? expressionWhenTrue : expressionWhenFalse
While it looks cool, it can also make the code less readable. Jad recommends avoiding it.