1/75
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
Associativity
-So what happens if the operators have the same precedence? JavaScript uses associativity to figure out the order to evaluate them tells JavaScript whether to evaluate operators from left to right or right to left. For most operators like addition and multiplication, associativity is left to right. So, JavaScript processes these from the leftmost side of the expression to the right: const result = 10 - 2 + 3; console.log(result); // 11
Right to left Associativity
Some operators, like assignment (=), are right-to-left associative. This means the right side of the expression gets evaluated first: let a, b; a = b = 5; console.log(a); // 5 console.log(b); // 5 console.log(a + b); // 10 The exponent operator is also right-to-left associative: const result = 2 ** 3 ** 2; console.log(result); // 512
The increment and decrement operators -
are represented by ++ and --, respectively. They both allow you to adjust the value of a variable by 1. Instead of writing something like x = x + 1 or x = x - 1, you can simply use x++ to add 1, or x-- to subtract 1. It's faster, cleaner, and easier to read.
Prefix (++x) -
increases the value of the variable first, then returns a new value. Prefix (++x) increases the value of the variable first, then returns a new value.
Postfix (x++) -
returns the current value of the variable first, then increases it.
Prefix examples
let x = 5; console.log(++x); // 6 console.log(x); // 6 In the code above, ++x means "increment x first, then use it". So when you log ++x, you immediately get the incremented value, which is 6.
Postfix (x++)
returns the current value of the variable first, then increases it.
Postfix example
Now, let's take a look at an example using the postfix: let y = 5; console.log(y++); // 5 console.log(y); // 6 In this example, y++ means "use y first, then increment it". When you log y++, you get 5, but y becomes 6 after that line of code.
The decrement operator
does the same thing as increment, except it decreases the value by 1. Again, there are two forms: prefix (--x) decreases the value of the variable first, then returns the new value. And postfix (x--) returns the current value first, then decreases it.
Decrement operator examples
let x = 5; console.log(--x); // 4 console.log(x); // 4 let y = 5; console.log(y--); // 5 console.log(y); // 4
Compound Operator
Notice how num += 2 combines both the addition and assignment steps into one. This saves time and reduces clutter in your code. Let's dive deeper into the most common compound assignment operators in JavaScript.
The subtraction assignment operator -=
subtracts the specified value from the current value of the variable and assigns the new value back to the variable: If you didn't use the subtraction assignment, you'd have done something like this: let score = 20; score = score - 7; console.log(score); // 13
The multiplication assignment operator
is represented by *=. It multiplies the current value of the variable by the specified number and reassigns it back to the variable:
division assignment operator denoted by /=
Just like others before it, it lets you divide the current value of a variable by a number you specify, then assign the result back to the variable:
Remainder assignment operator (%=)
which divides a variable by the specified number and assigns the remainder to the variable.
Exponent assignment operator (**=)
which raises a variable to the power of the specified number and reassigns the result to the variable.
Bitwise AND assignment operator (&=)
which performs a bitwise AND operation with the specified number and reassigns the result to the variable.
Bitwise OR assignment operator (|=)
which performs a bitwise OR operation with the specified number and reassigns the result to the variable
Booleans are a data type
with only true and false values. They're useful because they allow you to do something based on some conditions. Booleans are essential when you want to evaluate whether something should happen or not, like deciding if someone can access a certain feature in your app.
Example of Boolean
let isOldEnoughToDrive = true; console.log(isOldEnoughToDrive); // true. You can use this variable inside a conditional like this: let isOldEnoughToDrive = true; if (isOldEnoughToDrive) { console.log("You're old enough to drive"); // You're old enough to drive} else { console.log("Sorry, you are not old enough to drive"); }
This example uses what is called an if/else statement.
A conditional helps you make decisions in your code based on a condition. If isOldEnoughToDrive is true, then the sentence You're old enough to drive will be logged to the console. Otherwise, if the isOldEnoughToDrive is false, then the sentence Sorry, you are not old enough to drive will be logged to the console. Since the isOldEnoughToDrive variable is set to true, the first sentence will be logged to the console. You will learn more about if/else statements in a future lesson.
Equality
To compare two values, you can use either the equality or strict equality operator. The result of the comparison will be a boolean of either true or false. Here is an example of using the equality operator to compare a string and a number. The equality operator is represented by a double equals sign (==). console.log(5 == "5"); // true
Equality operator example
console.log(5 == "5"); // true JavaScript converts the string "5" into the number 5 and then checks if they are equal. Since both values are now the same, the result is true. The equality operator uses type coercion before checking if each value is equal.
Strict Equality Operator
This differs from the strict equality operator, which does not perform type coercion. The strict equality operator will check if the types are the same and if the values are the same. Here is an example using the strict equality operator to compare a number and string. This operator is represented by a triple equals sign (===). console.log(5 === '5'); // false
Inequality operator
first converts the string value to a number and then compares the values. Since the values would be the same it will return false. Example: console.log(5 != "5"); // false
Strict Inequality operator
The result would be true because the strict inequality operator does not perform any type coercion. Since the number 5 is not equal to the string "5", then the result is true. console.log(5 !== "5"); // true
Booleans
are a data type with only true and false values. They're useful because they allow you to do something based on some conditions.
Conditional statement
helps you make decisions in your code based on a condition. This example uses what is called an if/else statement. If isOldEnoughToDrive is true, then the sentence You're old enough to drive will be logged to the console. Otherwise, if the isOldEnoughToDrive is false, then the sentence Sorry, you are not old enough to drive will be logged to the console. Since the isOldEnoughToDrive variable is set to true, the first sentence will be logged to the console. You will learn more about if/else statements in a future lesson.
A switch statement
evaluates an expression and matches its value against a series of case clauses. When a match is found, the code block associated with that case is executed. A break statement should be placed at the end of each case, to terminate its execution and continue with the next. The default case is an optional case and only executes if none of the other cases match. The default case is placed at the end of a switch statement. const dayOfWeek = 3; switch (dayOfWeek) { case 1: console.log("It's Monday! Time to start the week strong."); break;
Comparison operators
allow you to compare two values and return a true or false result. You can then use the result to make a decision or control the flow of your program. You use comparisons in if statements, loops, and many other situations where you need to make decisions based on certain conditions.
The greater than operator
represented by a right-angle bracket (>), checks if the value on the left is greater than the one on the right:
The greater than or equal operator
represented by a right-angle bracket and the equals sign (>=), checks if the value on the left is either greater than or equal to the one on the right:
The lesser than operator
represented by a left-angle bracket (<) works similarly to >, but in reverse. It checks if the value on the left is smaller than the one on the right:
The less than or equal operator
represented by a left-angle bracket and the equals sign (<=) checks if the value on the left is smaller than or equal to the one on the right:
Truthy values
non-empty strings, Non-zero numbers, The Boolean true, arrays, objects
Falsey Values
“ “(empty string), 0, false, null, undefined, NaN
If statement
if (condition) { console.log("condition is truthy"); } When condition is a truthy value (non-empty string, non-zero number, true, etc.) the code within the if statement's body is executed.
Comparisons and undefined
A variable is undefined when it has been declared but hasn't been assigned a value. It's the default value of uninitialized variables and function parameters that weren't provided an argument. undefined converts to NaN in numeric contexts, which makes all numeric comparisons with undefined return false. console.log(undefined < 0); // false (NaN < 0 is false)
Comparisons and null
The null type represents the intentional absence of a value. null converts to 0 in numeric contexts, which may result in unexpected behavior in numeric comparisons: console.log(null < 0); // false (0 < 0 is false) console.log(null >= 0); // true (0 >= 0 is true)
Unary operators
act on a single operand to perform operations like type conversion, value manipulation, or checking certain conditions.
Unary plus operator
converts its operand into a number. If the operand is already a number, it remains unchanged. const str = '42'; const strToNum = +str; console.log(strToNum); // 42
Unary negation operator
It negates the value of the operand. It works similarly to the unary plus, except it flips the sign. const str = '42'; const strToNegativeNum = -str;
Unary logical NOT operator
represented by an exclamation mark (!), is another unary operator. It flips the boolean value of its operand. So, if the operand is true, it becomes false, and if it's false, it becomes true. let isOnline = true; console.log(!isOnline); // false
Unary bitwise NOT operator
Represented by a tilde, ~, it inverts the binary representation of a number. Computers store numbers in binary format (1s and 0s). The ~ operator flips every bit, meaning it changes all 1s to 0s and all 0s to 1s. const num = 5; // The binary for 5 is 00000101 console.log(~num); // -6. In this example, 5 became -6 because by applying the ~ operator to 5, you get - (5 + 1), which equals -6 due to two's complement representation. Two's complement is a way computers represent negative numbers in binary.
The void keyword
is a unary operator that evaluates an expression and returns undefined. const result = void (2 + 2); console.log(result); // undefined
If statement
takes a condition and runs a block of code if that condition is truthy.
else if,
if you want to check multiple conditions, you can use an block. const age = 15; if (age >= 18) { console.log("You're eligible to vote");
The ternary operator is a compact way to write simple if/else statements.
It has three parts: a condition, a result if the condition is true, and a result if it is false. Here's the basic syntax: condition ? expressionIfTrue : expressionIfFalse;
Example of Ternary operator
const temperature = 30; const weather = temperature > 25 ? 'sunny' : 'cool'; console.log(It's a ${weather} day!);
Best use for Ternary operator
Use a ternary while dealing with a single condition or single expressions, or when you want a compact syntax for simple logic.
Best use for if/else
Use if/else statements when you're dealing with complex conditions and multiple statements, as things become unreadable if you nest ternaries.
Binary logical operators
help you evaluate two expressions and return a result based on their truthiness. Let's look at the three most common binary logical operators: logical AND, logical OR, and the nullish coalescing operator.
The logical AND operator
is represented by a double ampersand (&&). It checks if both operands are true and returns a result. If both operands are truthy, it returns the second value, that is, the one on the right: const result = true && 'hello'; console.log(result); // hello
Zero AND operator
0 is a falsy value, the number 0 is logged to the console. And if both operands are falsy, it returns the first falsy value: const result = 0 && 3; console.log(result); // 0
The logical OR operator
checks if at least one of the operands is truthy. If the first operand is truthy, it returns that value: const result = 'This is truthy' || false; console.log(result); // This is truthy If the first operand is falsy but the second is truthy, the second value will be logged to the console:
nullish coalescing operator
is more sophisticated than logical OR and logical AND. Represented by a double question mark (??), it helps in scenarios where you want to return a value only if the first one is null or undefined. Here is an example of working with the nullish coalescing operator: const result = null ?? 'default'; console.log(result); // default
The Math.random()
method generates a random floating-point number between 0 (inclusive) and 1 (exclusive). This means the possible output can be 0, but it will never actually reach 1. Here is an example working with the Math.random() method: const randomNum = Math.random(); console.log(randomNum); // any number between 0 and 1 – 0 inclusive and 1 exclusive
Math.min() and Math.max()
both take a set of numbers and return the minimum and maximum value, respectively. Here is an example of working both of those methods:
Math.ceil() and Math.floor() methods
If you wanted to round numbers up or down to the nearest whole integer, you could use the .
Math.round()
is the hybrid of Math.ceil() and Math.floor(). It rounds a number to its nearest integer, taking the decimal point into account:
Math.trunc() method. Math.trunc()
removes the decimal part of a number, returning only the integer portion, without rounding
Math.sqrt() and Math.cbrt()
methods if you need to get the square root or cube root of a number, you can use the , respectively
Math.abs()
returns the absolute value of a number, turning negatives into positives.
Math.pow()
takes two numbers and raise the first to the power of the second.
How to generate a floating point between two numbers
Math.random() * (maximum - minimum) + minimum;
How to generate a floating point and set to a integer between two numbers
Math.floor(Math.random() *5 (maximum - minimum) + minimum;
NaN stands for "Not a Number"
It's a special value that represents an unrepresentable or undefined numerical result. NaN is a property of the global object, and it's also considered a type of number in JavaScript.
Example of NaN
NaN is typically the result of operations that should return a number but can't produce a meaningful numerical value. For example: let result = 0 / 0; console.log(result); // NaN.
Number.isNaN()
provides a more reliable way to check for NaN values, especially in cases where type coercion might lead to unexpected results with the global isNaN() function. let a = 0; let b = 0; let result = a / b; if (Number.isNaN(result)) { result = "Error: Division resulted in NaN"; } console.log(result); // "Error: Division resulted in NaN"
The isNaN() function property
is used to determine whether a value is NaN or not. However, it's important to understand how isNaN() works, as it can sometimes produce unexpected results. Here's how isNaN() behaves console.log(isNaN("37")); // false: "37" is converted to 37 console.log(isNaN("37.37")); // false: "37.37" is converted to 37.37
parseFloat()
This method parses a string argument and returns a floating-point number. It's designed to extract a number from the beginning of a string, even if the string contains non-numeric characters later on. These methods are particularly useful when dealing with user input or processing data that comes in string format but needs to be treated as numerical values. console.log(parseFloat("3.14 abc")); // 3.14
parseFloat() exceptions
If it can't find a valid number at the start of the string, it returns NaN (Not a Number).
parseInt()
on the other hand, parses a string argument and returns an integer. Like parseFloat(), it starts from the beginning of the string, but it stops at the first non-digit character. Both methods have some noteworthy behaviors. They ignore leading whitespace. They handle plus and minus signs at the beginning of the string.
.toFixed() method
is called on a number and takes one optional argument, which is the number of digits to appear after the decimal point. It returns a string representation of the number with the specified number of decimal places. let num = 3.14159; console.log(num.toFixed(2)); // "3.14"
.toFixed() cont. -
toFixed() returns a string, not a number. This is because the method is primarily intended for formatting numbers for display, not for further calculations. The .toFixed() method rounds the number to the nearest value that can be represented with the specified number of decimal places. This rounding behavior is important to understand console.log((3.14159).toFixed(3)); // "3.142" If you call .toFixed() without arguments, it defaults to 0 decimal places:
What is printed to the console from the code below?
const a = 2; if (1 == "1") { let b = 3; console.log(a + b); } console.log(b); Answer - The Scope Issue: The variable b is declared using let inside the if block, meaning it is block-scoped. It does not exist outside of those curly braces {}.