<>~==!!==Reference Javascript Comparison Operators
Reference Differences between forEach and for loop
function addTax(total) {
return total * 1.05;
}
addTax = 50;return addTax 50;addTax(50);addTax 50;Reference functions in javascript
let rate = 100;let 100 = rate;100 = let rate;rate = 100;Reference Javascript Assignment operators
var student = new Person();var student = construct Person;var student = Person();var student = construct Person();let modal = document.querySelector('#result');
setTimeout(function () {
modal.classList.remove('hidden');
}, 10000);
console.log('Results shown');
Reference Javascript is synchronous and single threaded
class Animal {
static belly = [];
eat() {
Animal.belly.push('food');
}
}
let a = new Animal();
a.eat();
console.log(/* Snippet Here */); //Prints food
a.prototype.belly[0]Object.getPrototype0f (a).belly[0]Animal.belly[0]a.belly[0]Reference Javascript Class static Keyword
Afor (var i = 1; i <= 4; i++) {
setTimeout(function () {
console.log(i);
}, i * 10000);
}
Bfor (var i = 1; i <= 4; i++) {
(function (i) {
setTimeout(function () {
console.log(j);
}, j * 1000);
})(j);
}
Cfor (var i = 1; i <= 4; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
Dfor (var i = 1; i <= 4; i++) {
(function (j) {
setTimeout(function () {
console.log(j);
}, j * 1000);
})(i);
}
Efor (var j = 1; j <= 4; j++) {
setTimeout(function () {
console.log(j);
}, j * 1000);
}
Alet discountPrice = function (price) {
return price * 0.85;
};
Blet discountPrice(price) {
return price * 0.85;
};
Clet function = discountPrice(price) {
return price * 0.85;
};
DdiscountPrice = function (price) {
return price * 0.85;
};
Reference defining javascript functions
var Storm = function () {};
Storm.prototype.precip = 'rain';
var WinterStorm = function () {};
WinterStorm.prototype = new Storm();
WinterStorm.prototype.precip = 'snow';
var bob = new WinterStorm();
console.log(bob.precip);
/[0-9]{2,}:[0-9]{2,}:[0-9]{2,}//\d\d:\d\d:\d\d//[0-9]+:[0-9]+:[0-9]+// : : /NOTE: The first three are all partially correct and will match digits, but the second option is the most correct because it will only match 2 digit time values (12:00:32). The first option would have worked if the repetitions range looked like [0-9]{2}, however because of the comma [0-9]{2,} it will select 2 or more digits (120:000:321). The third option will any range of time digits, single and multiple (meaning 1:2:3 will also match).
More resources:
'use strict';
function logThis() {
this.desc = 'logger';
console.log(this);
}
new logThis();
undefinedwindow{desc: "logger"}functionlet roadTypes = ['street', 'road', 'avenue', 'circle'];
Reference accessing javascript arrays
console.log(typeof 42);
'float''value''number''integer'Reference javascript data types
selfobjecttargetsourcefunction addNumbers(x, y) {
if (isNaN(x) || isNaN(y)) {
}
}
exception('One or both parameters are not numbers')catch('One or both parameters are not numbers')error('One or both parameters are not numbers')throw('One or both parameters are not numbers')JSON.fromString();JSON.parse()JSON.toObject()JSON.stringify()Reference convert json to javascript object
Reference javascript conditionals
for (var i = 0; i < 5; i++) {
console.log(i);
}
Reference javascript for loops
Object.get()Object.loop()Object.each()Object.keys()Reference javascript object static methods
var a = ['dog', 'cat', 'hen'];
a[100] = 'fox';
console.log(a.length);
Explanation: Map.prototype.size returns the number of elements in a Map, whereas Object does not have a built-in method to return its size.
Reference map methods javascript
const dessert = { type: 'pie' };
dessert.type = 'pudding';
Reference working with js objects
++--==||Reference short circuit javascript
Student.parent = Person;Student.prototype = new Person();Student.prototype = Person;Student.prototype = Person();Reference what is use strict in js
constvarletReference var vs let vs const in js
Boolean(0)Boolean("")Boolean(NaN)Boolean("false")thiscatchfunctionarrayReference implicit js parameters for functions
class X {
get Y() {
return 42;
}
}
var x = new X();
x.get('Y')x.Yx.Y()x.get().Ysum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
let diff = function (x, y) {
return x - y;
};
Reference accessing before initialization
Reference efficiency of lookups Explanation: Records in an object can be retrieved using their key which can be any given value (e.g. an employee ID, a city name, etc), whereas to retrieve a record from an array we need to know its index.
Reference async attribute for html
import _ from 'lodash';import 'lodash' as _;import '_' from 'lodash;import lodash as _ from 'lodash';Reference how to import library in js
[] == [];
Reference arrays in js are objects
Reference what are generators in nodejs
var v = 1;
var f1 = function () {
console.log(v);
};
var f2 = function () {
var v = 2;
f1();
};
f2();
Reference closures in js \/ nested functions
Reference functional programming
Explanation: You cannot invoke reduce on undefined object... It will throw (yourObject is not Defined...)
let arr = [];
typeofdeleteinstanceofvoidvar start = 1;
if (start === 1) {
let end = 2;
}
Reference block vs function scope
const x = 6 % 2;
const y = x ? 'One' : 'Two';
throwexceptioncatcherrorReference throwing errors in js
var a;
var b = (a = 3) ? true : false;
<p class="pull">lorem ipsum</p>
Document.querySelector('class.pull')document.querySelector('.pull');Document.querySelector('pull')Document.querySelector('#pull')let answer = true;
if (answer === false) {
return 0;
} else {
return 10;
}
Reference javascript conditionals
var start = 1;
function setEnd() {
var end = 10;
}
setEnd();
console.log(end);
function sayHello() {
console.log('hello');
}
console.log(sayHello.prototype);
function printA() {
console.log(answer);
var answer = 1;
}
printA();
printA();
1 then 11 then undefinedundefined then undefinedundefined then 1forEach() method differ from a for statement?Reference Differences between forEach and for loop
({}){}{ return {};}(({}))EXPLANATION: "to ensure that tasks further down in your code are not initiated until earlier tasks have completed" you use the normal (synchronous) flow where each command is executed sequentially. Asynchronous code allows you to break this sequence: start a long running function (AJAX call to an external service) and continue running the rest of the code in parallel.
[3] == [3]3 == '3'3 != '3'3 === '3'cancel()stop()preventDefault()prevent()attachNode()getNode()querySelector()appendChild()breakpassskipcontinue(a,b) => ca, b => {return c;}a, b => c{ a, b } => c! This is a comment# This is a comment\\ This is a comment// This is a commentReference comments in javascript
Reference javascript constructors
let a = 5;
console.log(++a);
button.addEventListener(
'click',
function (e) {
button.className = 'clicked';
},
false,
);
e.blockReload();button.preventDefault();button.blockReload();e.preventDefault();Reference events in javascript
function() { console.log('lorem ipsum'); }()();function() { console.log('lorem ipsum'); }();(function() { console.log('lorem ipsum'); })();Reference what is an Immediately Invoked Function Expression
Document.querySelector('img')Document.querySelectorAll('<img>')Document.querySelectorAll('img')Document.querySelector('<img>')function logThis() {
console.log(this);
}
logThis();
Reference what is the javascript window
const Greeting = ({ name }) => <h1>Hello {name}!</h1>;
class Greeting extends React.Component { render() { return <h1>Hello {this.props.name}!</h1>; } }class Greeting extends React.Component { constructor() { return <h1>Hello {this.props.name}!</h1>; } }class Greeting extends React.Component { <h>Hello {this.props.name}!</h>; } }class Greeting extends React.Component { render({ name }) { return <h1>Hello {name}!</h1>; } }var obj;
console.log(obj);
ReferenceError: obj is not defined{}undefinednullReference working with objects
class TaxCalculator {
static calculate(total) {
return total * 0.05;
}
}
Reference functions in javascript
const foo = {
bar() {
console.log('Hello, world!');
},
name: 'Albert',
age: 26,
};
console.log('I');
setTimeout(() => {
console.log('love');
}, 0);
console.log('Javascript!');
I
Javascript!
love
love
I
Javascript!
The output may change with each execution of code and cannot be determined.
.
I
love
Javascript!
Reference https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified especially see the ‘late timeouts’ section.
const foo = [1, 2, 3];
const [n] = foo;
console.log(n);
Reference array deconstruction
const foo = {
name: 'Albert',
};
Reference working with objects
map() and the forEach() methods on the Array prototype?forEach() method returns a single output value, whereas the map() method performs operation on each value in the array.forEach() method iterates through an array with no return value.forEach() method returns a new array with a transformation applied on each item in the original array, whereas the map() method iterates through an array with no return value.function makeAdder(x) {
return function (y) {
return x + y;
};
}
var addFive = makeAdder(5);
console.log(addFive(3));
<script></script><js></js><javascript></javascript><code></code>Reference Cross-Origin Resource Sharing
let rainForests = ['Amazon', 'Borneo', 'Cerrado', 'Congo'];
rainForests.splice(0, 2);
console.log(rainForests);
["Amazon","Borneo","Cerrado","Congo"]["Cerrado", "Congo"]["Congo"]["Amazon","Borneo"]const numbers = [1, 2, 3, 4, 5];
//MISSING LINE
const [one,two,three,four,five]=numbersconst {one,two,three,four,five}=numbersconst [one,two,three,four,five]=[numbers]const {one,two,three,four,five}={numbers}const obj = {
a: 1,
b: 2,
c: 3,
};
const obj2 = {
...obj,
a: 0,
};
console.log(obj2.a, obj2.b);
let animals = ['jaguar', 'eagle'];
//Missing Line
console.log(animals.pop()); //Prints jaguar
animals.filter(e => e === "jaguar");animals.reverse();animals.shift();animals.pop();Reference Javascript Array pop()
shift() - removes the FIRST element of an array and returns the removed item.
pop() - removes the LAST element of an array and returns the removed item.
reverse() - reverses the order of the elements in an array.
filter() - get every element in the array that meets the condition.
//Missing Line
for (var i = 0; i < vowels.length; i++) {
console.log(vowels[i]);
//Each letter printed on a separate line as follows;
//a
//e
//i
//o
//u
}
let vowels = "aeiou".toArray();let vowels = Array.of("aeiou");let vowels = {"a", "e", "i", "o", "u"};let vowels = "aeiou";const x = 6 % 2;
const y = x ? 'One' : 'Two';
console.log(y);
Note: this question is same with Q46.
Reference ternary operator js
let matrix = [["You","Can"],["Do","It"],["!","!","!"]];
matrix[1[2]]matrix[1][1]matrix[1,2]matrix[1][2]const animals = ['Rabbit', 'Dog', 'Cat'];
animals.unshift('Lizard');
let x = 6 + 3 + '3';
console.log(x);
var sound = 'grunt';
var bear = { sound: 'roar' };
function roar() {
console.log(this.sound);
}
bear.bind(roar);roar.bind(bear);roar.apply(bear);bear[roar]();a, b => { return c; }a, b => c{ a, b } => c(a,b) => c//some-file.js
export const printMe = (str) => console.log(str);
import printMe from './some-file';import { printMe } from './some-file';import default as printMe from './some-file';const printMe = import './some-file';Reference importing libraries in javascript
const arr1 = [2, 4, 6];
const arr2 = [3, 5, 7];
console.log([...arr1, ...arr2]);
[2, 3, 4, 5, 6, 7][3,5,7,2,4,6][3, 5, 7, 2, 4, 6][[2, 4, 6], [3, 5, 7]][2, 4, 6, 3, 5, 7]fetch()?done()then()finally()catch()array.slice()array.shift()array.push()array.replace()console.log(typeof 'blueberry');
stringarrayBooleanobject//HTML Markup
<div id="A">
<div id="B">
<div id="C">Click Here</div>
</div>
</div>
//JavaScript
document.querySelectorAll('div').forEach((e) => {
e.onclick = (e) => console.log(e.currentTarget.id);
});
const myNumbers = [1, 2, 3, 4, 5, 6, 7];
const myFunction = (arr) => {
return arr.map((x) => x + 3).filter((x) => x < 7);
};
console.log(myFunction(myNumbers));
[4,5,6,7,8,9,10][4,5,6,7][1,2,3,4,5,6][4,5,6]Reference functions in javascript
let rainForestAcres = 10;
let animals = 0;
while (rainForestAcres < 13 || animals <= 2) {
rainForestAcres++;
animals += 2;
}
console.log(animals);
Reference MDN JavaScript Looping code
let cipherText = [...'YZOGUT QGMORTZ MTRHTILS'];
let plainText = '';
/* Missing Snippet */
console.log(plainText); //Prints YOU GOT THIS
for (let key of cipherText.keys()) {
plainText += key % 2 === 0 ? key : ' ';
}
for (let [index, value] of cipherText.entries()) {
plainText += index % 2 !== 0 ? value : '';
}
for (let [index, value] of cipherText.entries()) {
plainText += index % 2 === 0 ? value : '';
}
for (let value of cipherText) {
plainText += value;
}
var pokedex = ['Snorlax', 'Jigglypuff', 'Charmander', 'Squirtle'];
pokedex.pop();
console.log(pokedex.pop());
Explanation: The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
<h1 class="content">LinkedIn Learning</h1>
<div class="content">
<span class="content">The LinkedIn Learning library has great JavaScript courses!</span>
</div>
[]undefined0nullconst lion = 1;
let tiger = 2;
var bear;
++lion;
bear += lion + tiger;
tiger++;
line 5, because lion cannot be reassigned a valueline 6, because the += operator cannot be used with the undefined variable bearline 5, because the prefix (++) operator does not exist in JavaScriptline 3, because the variable bear is left undefinedresult after running this code?const person = { name: 'Dave', age: 40, hairColor: 'blue' };
const result = Object.keys(person).map((x) => x.toUpperCase());
["Name", "Age", "HairColor"]["DAVE", 40, "BLUE"]["NAME", "AGE", "HAIRCOLOR"]let animals = ["eagle", "osprey", "salmon"];
let key = animal => animal === "salmon";
if(/* Insert Snippet Here */){
console.log("swim");
}
animals.every(key)animals.some(key).length === 1animals.filter(key) === trueanimals.some(key)Reference Array.prototype.some
class RainForest {
static minimumRainFall = 60;
}
let congo = new RainForest();
RainForest.minimumRainFall = 80;
console.log(congo.minimumRainFall);
undefined6080None of the above, as static is not a feature in Javascript.a.b on obj without throwing an error if a is undefined?let obj = {};
obj?.a.bobj.a?.bobj[a][b]obj.?a.?bReference Optional chaining (?.)
if (true) {
var x = 5;
const y = 6;
let z = 7;
}
console.log(x + y + z);
ReferenceError about x.18.undefined.ReferenceError about y.const x = [1, 2];
const y = [5, 7];
const z = [...x, ...y];
console.log(z);
[1,2,5,7][[1, 2], [5, 7]][2,7][2,1,7,5]const a = { x: 1 };
const b = { x: 1 };
a['x'] === b['x']a != ba === ba.x === b.xconsole.log(typeof 41.1);
Nothing. It resuults in a ReferenceError.decimalfloatnumberlet scores = [];
scores.push(1, 2);
scores.pop();
scores.push(3, 4);
scores.pop();
score = scores.reduce((a, b) => a + b);
console.log(score);
3467let bear = {
sound: 'roar',
roar() {
console.log(this.sound);
},
};
bear.sound = 'grunt';
let bearSound = bear.roar;
bearSound();
Nothing is printed to the console.gruntundefinedroarvar cat = { name: 'Athena' };
function swap(feline) {
feline.name = 'Wild';
feline = { name: 'Tabby' };
}
swap(cat);
console.log(cat.name);
var thing;
let func = (str = 'no arg') => {
console.log(str);
};
func(thing);
func(null);
const myFunc = () => {
const a = 2;
return () => console.log('a is ' + a);
};
const a = 1;
const test = myFunc();
test();
const myFunc = (num1, num2 = 2, num3 = 2) => {
return num1 + num2 + num3;
};
let values = [1, 5];
const test = myFunc(2, ...values);
console.log(test);
var flagsJSON =
'{ "countries" : [' +
'{ "country":"Ireland" , "flag":"🇮🇪" },' +
'{ "country":"Serbia" , "flag":"🇷🇸" },' +
'{ "country":"Peru" , "flag":"🇵🇪" } ]}';
var flagDatabase = JSON.parse(flagsJSON);
let conservation = true;
let deforestation = false;
let acresOfRainForest = 100;
if (/* Snipped goes here */){
++acresOfRainForest;
}
| [ ] !conservation | deforestation |
| [ ] deforestation && conservation | deforestation |
let cat = Object.create({ type: 'lion' });
cat.size = 'large';
let copyCat = { ...cat };
cat.type = 'tiger';
console.log(copyCat.type, copyCat.size);
let animals = [{ type: 'lion' }, 'tiger'];
let clones = animals.slice();
clones[0].type = 'bear';
clones[1] = 'sheep';
console.log(animals[0].type, clones[0].type);
console.log(animals[1], clones[1]);
a=5;
b=4;
alert(a++(+(+(+b))));
let cat = { type: "tiger", size: "large" };
let json = /* Snippet here */;
console.log(json); // print {"type":"tiger"}
cat.toJSON("type");JSON.stringify(cat, ["type"]);JSON.stringify(cat);JSON.stringify(cat, /type/);const obj1 = { first: 20, second: 30, first: 50 };
console.log(obj1);
print(typeof NaN);
<script type="text/javascript">a = 5 + "9"; document.write(a);</script>
function sum(num1, num2 = 2, num3 = 3) {
return num1 + num2 + num3;
}
let values = [1, 5];
let total = sum(4, ...values);
Reference: defer html script attribute
Reference: String.prototype.includes()
Reference: developer.mozilla Set
<h2 id="cleverest">girls</h2>
Reference: W3Schools HTML DOM Style color Property
var compare = function (test1, test2) {
// Missing line
};
compare(1078, '1078'); // yields true
test1==test2;if (true) {
var first = 'You';
}
function fScope() {
var second = 'got this!';
}
fScope();
console.log(first);
console.log(second);
const foo = () => console.log('First');
const bar = () => setTimeout(() => console.log('Second'), 0);
foo();
bar();
console.log('Third');
function scream(words) {
return words.toUpperCase() + '!!!';
}
scream('yay');
const obj = { a: 1, b: 2, c: 3 };
const { a, ...rest } = obj;
console.log(rest);
{ a: 1 }{ b: 2, c: 3 }{ a: 1, b: 2, c: 3 }undefinedReference Object Destructuring
map()filter()reduce()forEach()null and undefined?null is an assignment value representing no value, while undefined means a variable has been declared but not assigned a valueundefined is an assignment value, while null means undeclarednull is a string, undefined is a booleanconst promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve) => setTimeout(() => resolve('foo'), 1000));
const promise3 = Promise.resolve(42);
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
[3, 'foo', 42] immediately[3, 'foo', 42] after 1 second['foo', 3, 42] after 1 secondthis bindingthis from the enclosing scopeconst arr = [1, 2, 3, 4, 5];
const result = arr.reduce((acc, curr) => acc + curr, 0);
console.log(result);
[1, 2, 3, 4, 5]5150unshift()push()concat()splice()// math.js
export default function add(a, b) {
return a + b;
}
import add from './math.js';import { add } from './math.js';import * as add from './math.js';import default add from './math.js';const obj = {
name: 'John',
greet: function () {
console.log(`Hello, ${this.name}`);
},
};
const greetFunc = obj.greet;
greetFunc();
Hello, JohnHello, undefinedHello, TypeErrorhasOwnProperty()inexistscontainsconst obj = { name: 'John', age: 30 };
console.log('name' in obj); // true
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) => num * 2);
console.log(numbers);
console.log(doubled);
[1, 2, 3, 4, 5] and [2, 4, 6, 8, 10][2, 4, 6, 8, 10] and [2, 4, 6, 8, 10][1, 2, 3, 4, 5] and [1, 2, 3, 4, 5]undefined and [2, 4, 6, 8, 10]concat()flat()join()merge()const arr = [1, [2, 3], [4, [5, 6]]];
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6]
'Hello ' + name + '!'`Hello ${name}!`"Hello #{name}!"'Hello ${name}!'async function fetchData() {
try {
const data = await Promise.resolve('Success!');
console.log(data);
} catch (error) {
console.log('Error:', error);
}
}
fetchData();
Success!Error: Success!undefinedPromise { <pending> }find()filter()some()every()const set = new Set([1, 2, 2, 3, 3, 4]);
console.log(set.size);
console.log([...set]);
6 and [1, 2, 2, 3, 3, 4]4 and [1, 2, 3, 4]4 and {1, 2, 3, 4}6 and [1, 2, 3, 4]const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged);
{ a: 1, b: 2, c: 4 }{ a: 1, b: 3, c: 4 }{ a: 1, b: 2, b: 3, c: 4 }Error: duplicate property 'b'map()forEach()filter()reduce()new Promise(resolve => resolve(), 2000)new Promise(resolve => setTimeout(resolve, 2000))Promise.resolve().delay(2000)Promise.timeout(2000)const arr = [1, 2, 3];
arr.length = 5;
console.log(arr);
console.log(arr[4]);
[1, 2, 3, undefined, undefined] and undefined[1, 2, 3, <2 empty items>] and undefined[1, 2, 3, null, null] and nullError: Cannot set lengthevery()some()includes()find()const func = (a = 5, b = a * 2) => a + b;
console.log(func());
console.log(func(3));
15 and 915 and 915 and 15NaN and NaNconst weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj));
'value'undefined{}Error: WeakMap is not definedmap()forEach()filter()reduce()const generator = function* () {
yield 1;
yield 2;
yield 3;
};
const gen = generator();
console.log(gen.next().value);
console.log(gen.next().value);
1 and 21 and 1[1, 2, 3] and [1, 2, 3]undefined and undefinedcontains()includes()has()indexOf()const proxy = new Proxy(
{},
{
get(target, prop) {
return prop in target ? target[prop] : 'Property not found';
},
},
);
proxy.name = 'John';
console.log(proxy.name);
console.log(proxy.age);
'John' and 'Property not found''John' and undefinedundefined and 'Property not found'Error: Proxy is not definedconst arr = [1, 2, 3, 4, 5];
const [first, , third, ...rest] = arr;
console.log(first, third, rest);
1 3 [4, 5]1 2 [3, 4, 5]1 3 [2, 4, 5]1 undefined [4, 5]copy()clone()slice()duplicate()const original = [1, 2, 3];
const copy = original.slice();
const obj = {
counter: 0,
increment() {
this.counter++;
return this;
},
decrement() {
this.counter--;
return this;
},
};
obj.increment().increment().decrement();
console.log(obj.counter);
0123Number()parseInt()parseFloat()toInteger()const promise = Promise.reject('Error occurred');
promise
.then((result) => console.log('Success:', result))
.catch((error) => console.log('Caught:', error))
.finally(() => console.log('Finally executed'));
Success: Error occurred and Finally executedCaught: Error occurred and Finally executedFinally executed onlyError: Error occurredshift()pop()splice()slice()const func = async () => {
const result = await Promise.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.reject('Error'),
]);
return result;
};
func().catch((error) => console.log('Error:', error));
[1, 2, 'Error']Error: Error[1, 2, undefined]Promise rejectedReference Promise.all() with rejection
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set('key1', 'updated value');
console.log(map.size);
console.log(map.get('key1'));
3 and 'value1'2 and 'updated value'2 and 'value1'3 and 'updated value'every()some()filter()includes()const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;
obj.b = 3;
console.log(obj);
{ a: 2, b: 3 }{ a: 1 }{ a: 2 }Error: Cannot modify frozen objectmap()flatMap()flat()concat()const func = (x, y = x * 2, z = y + 1) => x + y + z;
console.log(func(2));
7119NaNExplanation: x=2, y=2*2=4, z=4+1=5, so 2+4+5=11
toString()join()concat()stringify()const regex = /\d+/g;
const str = 'abc123def456';
console.log(str.match(regex));
['123']['123', '456']['abc', 'def']nullconst arr = [1, 2, 3, 4, 5];
const result = arr.reduceRight((acc, curr) => acc + curr, 0);
console.log(result);
515[5, 4, 3, 2, 1]0unshift()push()concat()splice()const obj = {
name: 'John',
getName: () => {
return this.name;
},
};
console.log(obj.getName());
'John'undefined'getName'ErrorExplanation: Arrow functions don’t have their own this binding, so this refers to the global object, not the obj.
Reference Arrow Functions and this
Promise.all()Promise.race()Promise.allSettled()Promise.any()Reference Promise.allSettled()
// code here: function createCounter() { let count = 0; return { increment: () => count++, getValue: () => count }; }
const counter1 = createCounter(); const counter2 = createCounter();
counter1.increment(); counter1.increment(); counter2.increment();
console.log(counter1.getValue(), counter2.getValue());
Explanation: Each call to createCounter() creates a new closure with its own independent count variable. So: counter1 increments twice → 2 counter2 increments once → 1 Closures DO NOT share state unless they reference the same outer scope object.
[Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures]