【My Study Note】JavaScript
Contents
- 1. Seven Primitive Data Types in JavaScript
- 2. Operator
- 3. Condition Statement and Loop
- 4. Arrays
- 5. Objects
- 6. Math Object
- 7. Useful Strings Functions
- 8. Array Characteristics of Strings
- 9. Bugs and Errors
- 10. Error Handling
- 11. Var, Let, Const
- 12. Others
- 13. JavaScript Improvements (History)
- 14. Advanced Javascript Features
- 15. Module
Seven Primitive Data Types in JavaScript

Contents
String and Number data types

How can you make sure that the data shown on the screen is effectively stored so that the app you made can use it? Use the most suitable data types to achieve this.
What is Data?
Each piece of data in your app has a unique value, and while all values are collectively referred to as data, the values vary and therefore need to be stored differently.
Difference between them
- Text Values: String Data Type
- Numerical Values: Number Data Type
1st: The way you type values
To build a number, you simply type in the numerical values but to build a string in JavaScript, the characters must be enclosed in either single or double quotes.
2nd: Number of combinations that the number and string data types can store
The number data type has a very wide range in JS enough for most common use cases. However, it is limited up to a point determined by JavaScript calculation capabilities. The string data type practically has an unlimited number of combinations of characters. There is almost an infinite number of ways we can combine different characters into strings.
Number data type: Better suited for prices or any value that you would like to calculate.
Boolean Data Types
The Boolean data type has only two values, true and false. This means that it is helpful for making decisions.
Null Data Type
Null Data Type has the value “Null” and represents the absence of value. This is the intentional absence of value.
Undefined Data Type
Undefined data type can only hold the value undefined and usually refers to a variable that has not yet been assigned a value. It means the value does not exist in the compiler.
Difference between Null and Undefined
let a;
console.log(a); // undefined
let b = null;
console.log(b); // null
- Undefined: A variable that refers to something that doesn’t exist, and the variable isn’t defined to be anything.
- Null: A variable that is defined but is missing a value. (Intentionally, like literally by assigning the value “null”)
BigInt Data Type (New)
BigInt data type is like an extra large box that can accommodate a much greater range of numbers than the number data type. This is intended for use when integer values might exceed the range that is supported by the int data type.
Symbol Data Type (New)
Symbol data type can be used as a unique identifier. Think of it as having multiple boxes with the same label and using different serial numbers to avoid mixing them up.
Also, BigInt and Symbol are the new primitive data types to help with more complex tasks that version ES6 introduced.
Operators

Contents
- 1. Arithmetic Operators
- 2. Comparison Operators
- 3. Logical Operators
- 4. Strict Equality Operator vs Equality Operator
- 5. Inequality Operator
- 6. Addition Operator on a string and a number
Arithmetic Operators
Operator | Meaning | Example |
+ | Addition | 2+3 |
– | Subtraction | 3-2 |
/ | Division | 35/7 |
* | Multiplication | 7*4 |
Comparison Operators
Operator | Meaning | Example |
> | Greater than | 3>2 |
< | Less than | 2<3 |
== | Equal to | 5==5 |
!= | Not equal to | 5!=6 |
Logical Operators
Operator | Meaning | Example |
&& | Checks for both conditions to be true | a>5 && a<10 |
|| | Checks for at least one condition to be true | a>5 || a>10 |
! | Returns the false if the result is true | !(a>5) |
Strict Equality Operator vs Equality Operator
- Equality Operator: Having two equal signs and it only checks for the value and not the type(==)
- Strict Equality Operator: Having three equal signs and it checks for both the value and type(===)
100 == "100"
//Outcome: true
100 === "100"
//Outcome: false
Inequality Operator
It’s a combination of an exclamation mark and an equal sign(!= or !==).
1 != "1"
//Outcome: false
1 !== "1"
//Outcome: true
Addition Operator on a string and a number
Question
Using the + operator on a string and a number joins them together as if both of them were strings.
Condition Statement and Loop

Contents
- 1. Switch Statement
- 2. For Loop
- 3. While Loop
- 4. Nested Loop
Switch Statement
var place = "first";
switch (place) {
case "first":
console.log ("Gold");
break;
case "second":
console.log ("Silver");
break;
case "third":
console.log ("Bronze");
break;
default:
console.log ("No medal");
}
When to use?
When there’s a lot of conditions and want to write the code in a short way, that’s the time you should use. (Instead of using the if statement)
For Loop
for (var i = 0; i < 4; i ++) {
console.log (i);
}
While Loop
var i = 1;
while (i < 4) {
console.log (i);
i ++;
}
Nested Loop
// Outer Loop
for (var i = 0; i < 5; i ++) {
// Inner Loop
for (var j = 0; j < 3; j ++) {
console.log (i, j);
}
}
With using a nested loop, you can create a loop inside a loop. However, you need to take care not to overdo it as multiple levels of nested loops are not very performant. In other words, the more nested loops there are, the slower your code will run.
Iterables
Iterating Over a String
// Create a String
const name = "W3Schools";
for (x of name) {
console.log (x);
}
/* Output:
W
3
S
c
h
o
o
l
s */
Iterating Over an Array
// Create aa Array
const letters = ["a","b","c"];
for (x of letters) {
console.log (x);
}
// a
// b
// c
Object is not iterable
const car = {
speed: 100,
color: "blue"
}
for(prop of car) {
console.log(prop)
}
// Output: TypeError: car is not iterable
For of loop cannot work on an object directly, since an object is not iterable.
For in
const person = {fname:"John", lname:"Doe", age:25};
for (x in person) {
console.log (x);
}
/*
fname
lname
age
*/
The JavaScript for in statement loops through the properties of an Object:
Difference between "For of" and "For in"
For in
const car = {
engine: true,
steering: true,
speed: "slow"
}
const sportsCar = Object.create(car);
sportsCar.speed = "fast";
console.log (sportsCar);
// { speed: 'fast' }
for (prop in sportsCar) {
console.log (prop);
}
/*
speed
engine
steering
*/
For of
const car = {
engine: true,
steering: true,
speed: "slow"
}
const sportsCar = Object.create(car);
sportsCar.speed = "fast";
console.log (sportsCar);
// { speed: 'fast' }
for (prop of Object.keys(sportsCar)) {
console.log (prop);
}
// speed
Arrays

var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink'];
console.log (colors[0]);
// Outcome : red
How to add (push method)
var fruits = [];
fruits.push("apple"); // ['apple']
fruits.push('pear'); // ['apple', 'pear']
How to delete (pop method)
fruits.pop();
console.log(fruits); // ['apple']
Objects

var assistantManager = {
movement: 3,
socialSkills: 30,
streetSmarts: 30,
health: 40
}
console.log (assistantManager.movement);
If you have groups of data that you would like to relate, you can assign them to something known as an object.
Contents
- 1. Two ways to add new properties
- 2. Updating the property
- 3. Use functions with objects
- 4. Things you can do with Brackets Notation
Two ways to add new properties
1. Dot Operator
var storeManager = {};
storeManager.rangeTilesPerTurn = 4;
storeManager.socialSkills = 50;
storeManager.streetSmarts = 50;
storeManager.health = 30;
storeManager.specialAbility = "finding business opportunities";
storeManager.greeting = "Let's make some money";
The Brackets Notation
var house2 = {};
house2["rooms"] = 4;
house2['color']= "pink";
house2["priceUSD"] = 12345;
console.log(house2); // {rooms: 4, color: 'pink', priceUSD: 12345}
Updating the property
var car = {};
car.color = "red";
car["color"] = "green";
car["speed"] = 200;
car.speed = 100;
console.log(car); // {color: "green", speed: 100}
You can both access and update properties on objects using either the dot notation, or the brackets notation, or a combination of both.
Use functions with objects
var car = {};
car.mileage = 98765;
car.color = "red";
car.turnTheKey = function(name) {
console.log("The engine is running")
console.log (name);
}
console.log(car);
car.turnTheKey("Toyota");
Things you can do with Brackets Notation

You can add Space in property names(keys)
car["number of doors"] = 4;
console.log(car); // {color: 'green', speed: 100, number of doors: 5}
With the brackets notation, you can add space characters inside property names.
You can add Number in property names(keys)
car["2022"] = 1901;
console.log(car); // {2022: 1901, color: 'green', speed: 100, number of doors: 5}
Additionally, you can add numbers (as the string data type) as property keys. However, doing this is discouraged, due to obvious reasons of having a property key as a number string not really conveying a lot of useful information.
You can evaluate expressions
var arrOfKeys = ['speed', 'altitude', 'color'];
var drone = {
speed: 100,
altitude: 200,
color: "red"
}
for (var i = 0; i < arrOfKeys.length; i++) {
console.log(drone[arrOfKeys[i]])
}
// Outcome : 100 200 red
Lastly, like the example above, you can evaluate expressions.
Math Object

Contents
- Math PI
- Math.E
- Math.LN2
- Math.ceil()
- Math.floor()
- Math.round()
- Math.trunc()
- Moth.pow()
- Math.sqrt()
- Math.cbrt()
- Math.abs()
- Math.min()
- Math.max()
- Math.random()
Math PI
let x = Math.PI;
console.log (x);
// 3.141592653589793
Math.PI returns PI (the ratio of a circle's area to the square of its radius, approximately 3.14).
» Check Here for more information
Math.E
let x = Math.E;
console.log (x);
// 2.718281828459045
The Math.E property returns Euler's number which is approximately 2.718.
» Check Here for more information
Math.LN2
let x = Math.LN2;
console.log (x);
// 0.6931471805599453
The Math.LN2 propery returns the natural logarithm of 2 which is approximately 0.693.
» Check Here for more information
Math.ceil()
let x = Math.ceil(1.4);
console.log (x);
// 2
The Math.ceil() method rounds a number rounded UP to the nearest integer.
» Check Here for more information
Math.floor()
let x = Math.floor(1.6);
console.log (x);
// 1
The Math.floor() method rounds a number DOWN to the nearest integer.
» Check Here for more information
Math.round()
let x = Math.round(2.5);
console.log (x);
// 3
The Math.round() method rounds a number to the nearest integer.2.49 will be rounded down (2), and 2.5 will be rounded up (3).
» Check Here for more information
Math.trunc()
let x = Math.trunc(8.76);
console.log (x);
// 8
The Math.trunc() method returns the integer part of a number and trims the decimal.
» Check Here for more information
Moth.pow()
let x = Math.pow(4, 3);
console.log (x);
// 64
The Math.pow() method returns the value of x to the power of y.
» Check Here for more information
Math.sqrt()
let x = Math.sqrt(9);
console.log (x);
// 3
The Math.sqrt() method returns the square root of a number.
» Check Here for more information
Math.cbrt()
let x = Math.cbrt(125);
console.log (x);
// 5
The Math.cbrt() method returns the cubic root of a number.
» Check Here for more information
Math.abs()
let x = Math.abs(-7.25);
console.log (x);
// 7.25
The Math.abs() method returns the absolute value of a number.
» Check Here for more information
Math.min()
let x = Math.min(5, 10);
console.log (x);
// 5
The Math.min() method returns the number with the lowest value.
» Check Here for more information
Math.max()
let x = Math.max(5, 10);
console.log (x);
// 10
The Math.max() method returns the number with the highest value.
» Check Here for more information
Math.random()
let x = Math.random();
let y = Math.floor((Math.random() * 10) + 1);
console.log (x);
console.log (y);
// x: 0.9039766005218235, y: 6
The Math.random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).
» Check Here for more information
Useful Strings Functions

Contents
charAt()
let text = "HELLO WORLD";
let letter = text.charAt(0);
console.log (letter);
// H
The charAt() method returns the character at a specified index (position) in a string.
» Check Here for more information
concat()
let text1 = "sea";
let text2 = "food";
let result = text1.concat(text2);
console.log (result);
// seafood
The concat() method joins two or more strings.
» Check Here for more information
// You can create arrays with using Concat
var example = ["abc"].concat(["def"]);
console.log (example);
// Output: [ 'abc', 'def' ]
var example2 = ["abc"] + ["def"];
console.log (example2);
// Output: abcdef
indexOf()
let x = "ho-ho-ho".indexOf('h');
let y = "ho-ho-ho".indexOf('o');
let z = "ho-ho-ho".indexOf('-');
console.log (x, y, z);
// 0 1 2
The indexOf returns the location of the first position that matches a character.
» Check Here for more information
lastIndexOf()
let text = "Hello planet earth, you are a great planet.";
let result = text.lastIndexOf("planet");
console.log (result);
// 36
The lastIndexOf() method searches the string from the end to the beginning.
» Check Here for more information
split()
let x = "ho-ho-ho".split("-");
console.log (x);
// [ 'ho', 'ho', 'ho' ]
The split() method splits a string into an array of substrings.
» Check Here for more information
toUpperCase()
let text = "Hello World!";
let result = text.toUpperCase();
console.log (result);
// HELLO WORLD!
The toUpperCase() method converts a string to uppercase letters.
» Check Here for more information
toLowerCase()
let text = "Hello World!";
let result = text.toLowerCase();
console.log (result);
// hello world!
The toLowerCase() method converts a string to lowercase letters.
» Check Here for more information
Array Characteristics of Strings
In the world of JavaScript, it can often be said that strings behave like arrays as strings are array-like.
Array
var letters = ['a', 'b', 'c'];
for (var i = 0; i < letters.length; i ++) {
console.log (letters[i]);
}
// a b c
String
var letters = "abc";
for (var i = 0; i < letters.length; i ++) {
console.log (letters[i]);
}
// a b c
As an output, both of them are the same.
Things you cannot do
var greet = "Hello";
console.log (greet.pop());
// This doesn't work
Strings are like Arrays. But, you can't run all the array methods on strings. For example, the pop method.
Things you can do
var greet = "Hello";
var user = "Lisa";
console.log (greet + user);
// HelloLisa
console.log (greet.concat(user));
// HelloLisa
But on the other hand, you can also run some array methods on strings. For example, the concat method.
Bugs and Errors

Contents
Bugs
function addNums (a, b) {
console.log (a + b);
}
addNums ("11", 5);
// 115
Like the example above, our program is working without interruption. However, it is not working how we intended it to work. This is what's referred to as a bug, as it makes our code behave unexpectedly, but it continues to work.
Errors

When an error happens, our program stops executing the code as a direct consequence. No further lines of code are executed. JavaScript does its best with reporting errors by outputting an error message to the console. This error reporting is useful because it narrows down the issue with our code.
4 most common error messages
Syntax Error
var country = "Japan;
console.log (country);
// SyntaxError: Invalid or unexpected token
Like the example above, a syntax error occurs when you write a piece of code that JavaScript cannot read.
Type Error
let num = 1;
let upperCase = num.toUpperCase(); // number cannot be the uppercase
console.log (upperCase);
// TypeError: num.toUpperCase is not a function
Like the example above, a type error is thrown if you use a value that is outside the range of expected types.
Reference Error
console.log (c + d);
// ReferenceError: c is not defined
Like the example above, a reference error occurs when a value is not defined, but you attempt to use it in your code.
Range Error
var binary = (10).toString(2);
console.log (binary);
// 1010
var number = (10).toString(100);
console.log (number);
// RangeError: toString() radix argument must be between 2 and 36
Like the example above, a range rrror is thrown when we're giving a value to a function, but that value is out of the allowed range of acceptable input values.
Error Handling
You may recall that when your code contains an error, it stops running. However, in JavaScript, there are some built in statements to help your code continue to run even if an error occurs.
- The try statement defines the code block to run (to try).
- The catch statement defines a code block to handle any error.
- The finally statement defines a code block to run regardless of the result.
- The throw statement defines a custom error.
- Both catch and finally are optional, but you must use one of them.
For try...catch to work, the code must be runnable. In other words, it should be valid JavaScript.
Example 1
try {
console.log (a + b);
} catch (err) {
console.log (err);
console.log ("There was an error");
}
console.log ("My program doesn't stop");
// ReferenceError: a is not defined
// There was an error
// My program doesn't stop
Example 2
try {
throw new ReferenceError();
} catch (err) {
console.log (err);
console.log ("There was an error");
}
console.log ("My program doesn't stop");
// ReferenceError
// There was an error
// My program doesn't stop
Example 3
function addTwoNums(a, b) {
try {
if (typeof(a) !== 'number') {
throw new ReferenceError('the first argument is not a number');
} else if (typeof(b) !== 'number') {
throw new ReferenceError('the second argument is not a number');
} else {
console.log("Error!", err);
}
} catch (err) {
console.log (err);
}
}
addTwoNums(5, "5");
console.log ("It still works");
// ReferenceError: the second argument is not a number
// It still works
Get the slight idea of what this is
» Check this for the example code
Var, Let, Const
- 1. You can use var in your code even before it is declared.
- 2. You can redeclare the same variable when you use VAR.
- 3. The variables are basically only scoped to a function or if they are declared outside the function their scope is global.
You can use it in your code even before it is declared.
Using Var
console.log (country);
var country = "Japan";
// Output: undefined
Using Let or Const
If you use "let" or "const", it would be ReferenceError.
console.log (country);
let country = "Japan";
// ReferenceError: Cannot access 'country' before initialization
You can redeclare the same variable when you use VAR.
Using Var
var country = "Japan";
var country = "Australia";
console.log (country);
// Output: Australia
Using Let or Const
let country = "Japan";
let country = "Australia";
console.log (country);
// SyntaxError: Identifier 'country' has already been declared
The variables are basically only scoped to a function or if they are declared outside the function their scope is global.
Using Var
var food = "ramen";
function example() {
var country = "Japan";
}
console.log (country);
// Output: ReferenceError: country is not defined
var food = "ramen";
if (food == "ramen") {
var name = "ten";
}
console.log (name);
// Output: ten
Using Let or Const
var food = "ramen";
function example() {
let country = "Japan";
}
console.log (country);
// Output: ReferenceError: country is not defined
var food = "ramen";
if (food == "ramen") {
let name = "ten";
}
console.log (name);
// ReferenceError: name is not defined
With using the var, if you declare it inside the if statements or loops, like the for or while loops, it's not gonna be local scope. Meaning, you can use it outside the statement. However, only functions, if you declare var inside the function, you cannot use it from outside the function. With using the let or const, even within an if statement or loops, you cannot access the variable which is declared in it from outside.
Difference between Let and Const
Use let if the value might change in the future, and use const if the value will never change.
Others

Number Data Type: Power
var number = 10 ** 2;
console.log (number);
// 100
For example, 10 to the power of 2, 10 times 10 will return 100.
Typeof
var type = typeof ("John");
console.log (type);
// string
Typeof operator returns the type of the value.
» Check Here for the code
Emojis
You can check the emoji's code from here.
JavaScript Improvements (History)

What you can learn
- History of JavaScript
- Importance of ECMA (European Computer Manufacturers Association) and ECMAScript.
JavaScript is a programming language that had humble beginnings.
It was built in only 10 days in 1995 by a single person, Brendan Eich, who was tasked with building a simple scripting language to be used in version 2 of the Netscape browser. It was initially called LiveScript, but since the Java language was so popular at the time, the name was changed to JavaScript - although Java and JavaScript are in no way related.
For the first few years, after it was built, JavaScript was a simple scripting language to add mouseover effects and other interactivity. Those effects were being added to webpages using the <script> HTML element.
Inside each of the script elements, there could be some JavaScript code. Due to the rule that HTML, CSS, and JavaScript must be backward compatible, even the most advanced code written in JavaScript today ends up being written between those script tags.
Over the years, JavaScript grew ever more powerful, and in recent times, it's continually touted as among the top three commonly used languages.
In 1996 Netscape made a deal with the organization known as ECMA (European Computer Manufacturers Association) to draft the specification of the JavaScript language, and in 1997 the first edition of the ECMAScript specification was published.
ECMA publishes this specification as the ECMA-262 standard.
You can think of a standard as an agreed-upon way of how things should work. Thus, ECMA-262 is a standard that specifies how the JavaScript language should work.
There have been 12 ECMA-262 updates - the first one was in 1997.
JavaScript as a language is not a completely separate, stand-alone entity. It only exists as an implementation. This implementation is known as a JavaScript engine.
Traditionally, the only environment in which it was possible to run a JavaScript engine, was the browser. More specifically, a JavaScript engine was just another building block of the browser. It was there to help a browser accomplish its users' goal of utilizing the internet for work, research, and play.
So, when developers write JavaScript code, they are using it to interact with a JavaScript engine. Put differently, developers write JavaScript code so that they can "talk to" a JavaScript engine.
Additionally, the JavaScript engine itself comes with different ways to interact with various other parts of the browser. These are known as Browser APIs.
Thus, the code that you write in the JavaScript programming language allows you to do 2 things.
- To interact with the JavaScript engine inside of the browser
- To interact with other browser functionality that exists outside of the JavaScript engine, but is still inside the browser.
Although traditionally it was possible to interact with the JavaScript engine only inside of the browser, this all changed in 2009, when Node.js was built by Ryan Dahl.
He came up with a way to use a JavaScript engine as a stand-alone entity. Suddenly, it was possible to use JavaScript outside of the browser, as a separate program on the command line, or as a server-side environment.
Today, JavaScript is ubiquitous and is running in browsers, on servers, actually, on any device that can run a JavaScript engine.
Advanced Javascript Features
De-structuring arrays and objects
// This makes it possible to unpack values from arrays, or properties from objects, into distinct variables. (Duplicating it)
let {PI} = Math;
console.log (PI);
// Output: 3.141592653589793
// More specified example to understand
var user = {name: "Swift", gender: "female", age:29};
var {name} = user;
console.log (name);
// Output: Swift
name = "Harry";
console.log (name == user[name]);
// Output: false (Because when you unpack the values, you are just duplicating it. and they are not syncronized)
Built-in methods
Object.keys()
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
console.log (Object.keys(person));
// Output: [ 'firstName', 'lastName', 'age', 'eyeColor' ]
The Object.keys() method returns an Array Iterator object with the keys of an object.
Object.values()
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
console.log (Object.values(person));
// Output: [ 'John', 'Doe', 50, 'blue' ]
Object.entries()
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
console.log (Object.entries(person));
/* Output:
[
[ 'firstName', 'John' ],
[ 'lastName', 'Doe' ],
[ 'age', 50 ],
[ 'eyeColor', 'blue' ]
]
*/
The values that get returned are 2-member arrays nested inside an array. In other words, you get an array of arrays, where each array item has two members, the first being a property's key, and the second being a property's value.
Object.create()
const car = {
engine: true,
steering: false,
speed: "slow"
}
const sportsCar = Object.create(car);
sportsCar.speed = "fast";
console.log (sportsCar);
// Output: { speed: 'fast' }
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
console.log (fruits);
// Map(3) { 'apples' => 500, 'bananas' => 300, 'oranges' => 200 }
console.log(fruits.get("bananas"));
// 300
Map is like an array because it's iterable. However, it consists of key value pairs. It's important not to confuse a map with an object. With maps any value can be used as a key. With objects, keys can only be strings or symbols.
var result = [0,10,20,30,40,50].map( function(num) {
return num / 10
})
console.log (result);
// [ 0, 1, 2, 3, 4, 5 ]
This method is used to map each array item over to another array's item, based on whatever work is performed inside the function that is passed-in to the map as a parameter.
Set
// Create a Set
const letters = new Set(["a","b","c"]);
letters.add("s");
console.log (letters);
// Set(4) { 'a', 'b', 'c', 's' }
letters.add("a");
console.log (letters);
// Set(4) { 'a', 'b', 'c', 's' } Nothing would be changed
Set is a collection where each item in the collection must be unique. For example, if you try to add a non unique item to a set, this operation will simply not be run. In other words, no errors will be thrown and no updates will be made to a set.
ForEach
const fruits = ['kiwi','mango','apple','pear'];
function appendIndex(fruit, index) {
console.log(`${index}. ${fruit}`)
}
fruits.forEach(appendIndex);
/*
0. kiwi
1. mango
2. apple
3. pear
*/
The forEach() method accepts a function that will work on each array item. That function's first parameter is the current array item itself, and the second (optional) parameter is the index.
Filter
const nums = [0,10,20,30,40,50];
var result = nums.filter( function(num) {
return num > 20;
})
console.log (result);
// [ 30, 40, 50 ]
The filter() method creates a new array filled with elements that pass a test provided by a function.
Looping over any object's own property keys and values
var clothingItem = {
price: 50,
color: 'beige',
material: 'cotton',
season: 'autumn'
}
for( key of Object.keys(clothingItem) ) {
console.log(key, ":", clothingItem[key])
}
/* Output:
price : 50
color : beige
material : cotton
season : autumn
*/
Ternary Operator
//Syntax
condition ? true : false;
//Example
var dynamicKey = Math.random() > 0.5 ? "speed" : "color";
The term ternary means composed of three items or parts. The ? operator is also called the ternary operator because, unlike other operators such as strict equal (===) or remainder (%), it's the only one that takes three operands.
Starting with ?, we add a condition on the left side and a value on the right side to return when the condition is true. Then we add a colon (:) followed by a value to return if the condition is false.
Randomly accessing the objects
function testBracketsDynamicAccess() {
var dynamicKey = Math.random() > 0.5 ? "speed" : "color";
var drone = {
speed: 15,
color: "orange"
}
console.log(drone[dynamicKey]);
}
testBracketsDynamicAccess();
// Output: 15 (sometimes: orange)
Template literals
// Until ES6, 2 ways to build string
"Hello World"
'Hello World'
// ES6 introduced the use of backtick characters as delimiters (new ways to build string)
`Hello World`
Template literals are an alternative way of working with strings, which was introduced in the ES6 addition to the JavaScript language.
Difference between them
- Variable Interpolation
- Multiple Lines
- Expression Evaluation
Variable Interpolation
// ES5
var greet = "Hello";
var place = "World";
console.log(greet + " " + place + "!");
// Hello World!
// ES6
console.log(`${greet} ${place}!`)
// Hello World!
Multiple Lines
var greet = `Hello,
World
!
`;
console.log (greet);
/*
Hello,
World
! */
Expression Evaluation
console.log(`${1 + 1 + 1 + 1 + 1} stars!`);
// 5 stars!
This opens up a host of possibilities. For example, it's possible to evaluate a ternary expression inside a template literal.
Converting an object to an array
const result = [];
const drone = {
speed: 100,
color: 'yellow'
}
const droneKeys = Object.keys(drone);
droneKeys.forEach( function(key) {
result.push(key, drone[key])
})
console.log(result);
// [ 'speed', 100, 'color', 'yellow' ]
Working with Maps in JavaScript
let bestBoxers = new Map();
bestBoxers.set(1, "The Champion");
bestBoxers.set(2, "The Runner-up");
bestBoxers.set(3, "The third place");
console.log(bestBoxers);
/*
Map(3) {
1 => 'The Champion',
2 => 'The Runner-up',
3 => 'The third place'
}
*/
Working with Sets in JavaScript
new Set();
const repetitiveFruits = ['apple','pear','apple','pear','plum', 'apple'];
const uniqueFruits = new Set(repetitiveFruits);
console.log(uniqueFruits);
Set(3) { 'apple', 'pear', 'plum' }
We can use "sets" to quickly filter an array for unique members.
Spread Operator
const country = ["Japan", "Australia", "Canada"];
function countries (country1, country2, country3) {
for (var i = 1; i <4; i ++) {
console.log (country[i]);
}
}
countries (...country);
/*
Australia
Canada
undefined
*/
The advantage of this approach is that you don't have to list each individual member of the array that you want to pass to your function. The syntax is clear, concise, and easy to type.
Rest Operator
const country = ["Japan", "Australia", "Canada", "Thailand", "Philippines", "US", "UK"];
const [] = country;
const [first, second, third, ...SecondVisit] = country;
console.log (first);
// Japan
console.log (second, third);
// Australia Canada
console.log (SecondVisit);
// [ 'Thailand', 'Philippines', 'US', 'UK' ]
This is conducted by "De-structing" and using the "rest operator".
function addTaxToPrices(taxRate, ...itembought) {
return itembought.map(item => taxRate * item);
}
let shoppingCart = addTaxToPrices(1.08, 100, 200, 1800);
console.log (shoppingCart);
// [ 108, 216, 1944.0000000000002 ]
Concatenating arrays
const fruits = ['apple', 'pear', 'plum']
const berries = ['blueberry', 'strawberry']
const fruitsAndBerries = [...fruits, ...berries] // concatenate
console.log(fruitsAndBerries);
// ['apple', 'pear', 'plum', 'blueberry', 'strawberry']
Concatenating objects
const flying = { wings: 2 }
const car = { wheels: 4 }
const flyingCar = {...flying, ...car}
console.log(flyingCar)
// {wings: 2, wheels: 4}
Adding new members to arrays without using the push() method
let veggies = ['onion', 'parsley'];
veggies = [...veggies, 'carrot', 'beetroot'];
console.log(veggies);
// ['onion', 'parsley', 'carrot', 'beetroot']
Convert a string to an array using the spread operator
const greeting = "Hello";
const arrayOfChars = [...greeting];
console.log(arrayOfChars); // ['H', 'e', 'l', 'l', 'o']
Copying either an object or an array into a separate one
const car1 = {
speed: 200,
color: 'yellow'
}
const car2 = {...car1}
car1.speed = 201
console.log(car1.speed, car2.speed)
// 201 200
Module
In JavaScript, complex programs can be useful for multiple applications and it wouldn't make sense to rewrite them over and over. Thankfully, since version ES6, they can be saved and used elsewhere as modules.
How it works
JavaScript modules are standalone units of code that you can reuse again and again. Being standalone means that you can add them to your program, remove them and replace them with other modules and everything will still work.
Limitation of module
You have to run the code over a server. (You can use local server for that)
How to use basic ES6 module
<script type="module">
import {informalGreeting} from './greeting.js';
informalGreeting("Jane");
// Hello, Jane;
</script>