Sample repo with JavaScript samples and sandbox project. For details see individual project README files.
JavaScript Fundamentals from Mark Zamoyta course on Pluralsight.
const carId = 42;
You can either use var
or let
. The difference is that let
has scoping, which means you can't use the variable outside the scope it is defined in.
// you can only use the variable after it was defined
// console.log(carId);
let carId = 42;
// you can use the variable before to get `undefined` value
console.log(carId); // undefined
var carId = 42;
function sendCars(day, ...allCarIds) {
allCarIds.forEach( id => console.log(id));
}
sendCars('Monday', 100, 200, 555);
Desctructuring arrays example:
let carIds = [1, 2, 5];
let car1, remainingCars;
[car1, ... remainingCars] = carIds;
console.log(car1, remainingCars);
Destructuring objects example:
let car = { id: 5000, style: 'convertible' };
let {id, style} = car;
console.log(id, style);
The oposite to destructuring is spreading:
function startCars(car1, car2, car3) {
console.log(car1, car2, car3);
}
let carIds = [100, 30, 500];
startCars(...carIds); // 100 30 500
let carCodes = 'abc';
startCars(...carCodes); // a b c
Returns type of a variable, constant or a literal value:
typeof(1)
: numbertypeof(true)
: booleantypeof('Hello')
: stringtypeof( function() {})
: functiontypeof({})
: objecttypeof(null)
: objecttypeof(undefined)
: undefinedtypeof(NaN)
: number
// convert to string
foo.toString();
// convert string to integer
Number.parseInt('55'); // 55 as a number
// convert string to number
Number.parseFloat('55.99'); // 55.99 as a number
Simple for loops:
for (let i=0; i<4; i++) {
if (i === 2) {
continue;
}
console.log(i);
}
var1 == var2
: it will do the necessary conversion before doing the comparisonvar1 === var2
: it will only compare values (no conversion is done)
Similarly for inequality, !=
and !==
.
console.log(1 == 1); // true
console.log(1 == true); // true
console.log(1 === true); // false
Same as any other language, like i++
, ++i
, -i
, etc.
&&
: logical AND operator||
: logical OR operator
Same as any other language, like <
, <=
, etc.
Same as any other language, (condition ?
then :
else).
Same as any other language, like +=
, -=
, /=
, etc.
See Mozilla documentation for table with operator precedence.
IIFE stands for Immediately Invoked Function Expression.
// just function
function() {
console.log('in function');
}
// iife - executed immediately
(function() {
console.log('in function');
})();
let app = (function() {
let carId = 123;
let getId = function() {
return carId;
};
return {
getId: getId
};
})();
console.log(app.getId());