Welcome to JavaScript quiz! Are you ready to put your JavaScript skills to the test? This quiz will challenge your knowledge of how it behaves in various scenarios. Be prepared for some tricky questions that will require you to think critically about JavaScript's nuances.
function sayHi() {
console.log(name);
console.log(age);
var name = 'Lydia';
let age = 21;
}
sayHi();
Lydia and undefinedLydia and ReferenceErrorReferenceError and 21undefined and ReferenceError
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
0 1 2 and 0 1 20 1 2 and 3 3 33 3 3 and 0 1 2
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};
console.log(shape.diameter());
console.log(shape.perimeter());
20 and 62.8318530717958620 and NaN20 and 63NaN and 63
+true;
!'Lydia';
1 and falsefalse and NaNfalse and false
const bird = {
size: 'small',
};
const mouse = {
name: 'Mickey',
small: true,
};
mouse.bird.size is not validmouse[bird.size] is not validmouse[bird["size"]] is not valid
let c = { greeting: 'Hey!' };
let d;
d = c;
c.greeting = 'Hello';
console.log(d.greeting);
HelloHey!undefinedReferenceErrorTypeError
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
true false truefalse false truetrue false falsefalse true true
class Chameleon {
static colorChange(newColor) {
this.newColor = newColor;
return this.newColor;
}
constructor({ newColor = 'green' } = {}) {
this.newColor = newColor;
}
}
const freddie = new Chameleon({ newColor: 'purple' });
console.log(freddie.colorChange('orange'));
orangepurplegreenTypeError
let greeting;
greetign = {}; // Typo!
console.log(greetign);
{}ReferenceError: greetign is not definedundefined
function bark() {
console.log('Woof!');
}
bark.animal = 'dog';
SyntaxError. You cannot add properties to a function this way."Woof" gets logged.ReferenceError
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const member = new Person('Lydia', 'Hallie');
Person.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
console.log(member.getFullName());
TypeErrorSyntaxErrorLydia Hallieundefined undefined
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const lydia = new Person('Lydia', 'Hallie');
const sarah = Person('Sarah', 'Smith');
console.log(lydia);
console.log(sarah);
Person {firstName: "Lydia", lastName: "Hallie"} and undefinedPerson {firstName: "Lydia", lastName: "Hallie"} and Person {firstName: "Sarah", lastName: "Smith"}Person {firstName: "Lydia", lastName: "Hallie"} and {}Person {firstName: "Lydia", lastName: "Hallie"} and ReferenceError
function sum(a, b) {
return a + b;
}
sum(1, '2');
NaNTypeError"12"3
let number = 0;
console.log(number++);
console.log(++number);
console.log(number);
1 1 21 2 20 2 20 1 2
function getPersonInfo(one, two, three) {
console.log(one);
console.log(two);
console.log(three);
}
const person = 'Lydia';
const age = 21;
getPersonInfo`${person} is ${age} years old`;
"Lydia" 21 ["", " is ", " years old"]["", " is ", " years old"] "Lydia" 21"Lydia" ["", " is ", " years old"] 21
function checkAge(data) {
if (data === { age: 18 }) {
console.log('You are an adult!');
} else if (data == { age: 18 }) {
console.log('You are still an adult.');
} else {
console.log(`Hmm.. You don't have an age I guess`);
}
}
checkAge({ age: 18 });
You are an adult!You are still an adult.Hmm.. You don't have an age I guess
function getAge(...args) {
console.log(typeof args);
}
getAge(21);
"number""array""object""NaN"
function getAge() {
'use strict';
age = 21;
console.log(age);
}
getAge();
21undefinedReferenceErrorTypeError
const sum = eval('10*10+5');
105"105"TypeError"10*10+5"
sessionStorage.setItem('cool_secret', 123);
var num = 8;
var num = 10;
console.log(num);
810SyntaxErrorReferenceError
const obj = { 1: 'a', 2: 'b', 3: 'c' };
const set = new Set([1, 2, 3, 4, 5]);
obj.hasOwnProperty('1');
obj.hasOwnProperty(1);
set.has('1');
set.has(1);
false true false truefalse true true truetrue true false truetrue true true true
const obj = { a: 'one', b: 'two', a: 'three' };
console.log(obj);
{ a: "one", b: "two" }{ b: "two", a: "three" }{ a: "three", b: "two" }SyntaxError
for (let i = 1; i < 5; i++) {
if (i === 3) continue;
console.log(i);
}
1 21 2 31 2 41 3 4
String.prototype.giveLydiaPizza = () => {
return 'Just give Lydia pizza already!';
};
const name = 'Lydia';
console.log(name.giveLydiaPizza())
"Just give Lydia pizza already!"TypeError: not a functionSyntaxErrorundefined
const a = {};
const b = { key: 'b' };
const c = { key: 'c' };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
123456undefinedReferenceError
const foo = () => console.log('First');
const bar = () => setTimeout(() => console.log('Second'));
const baz = () => console.log('Third');
bar();
foo();
baz();
First Second ThirdFirst Third SecondSecond First ThirdSecond Third First
<div onclick="console.log('first div')">
<div onclick="console.log('second div')">
<button onclick="console.log('button')">
Click!
</button>
</div>
</div>
divdivbutton
<div onclick="console.log('div')">
<p onclick="console.log('p')">
Click here!
</p>
</div>
p divdiv ppdiv
const person = { name: 'Lydia' };
function sayHi(age) {
return `${this.name} is ${age}`;
}
console.log(sayHi.call(person, 21));
console.log(sayHi.bind(person, 21));
undefined is 21 Lydia is 21function functionLydia is 21 Lydia is 21Lydia is 21 function
function sayHi() {
return (() => 0)();
}
console.log(typeof sayHi());
"object""number""function""undefined"
0;
new Number(0);
('');
(' ');
new Boolean(false);
undefined;
0, '', undefined0, new Number(0), '', new Boolean(false), undefined0, '', new Boolean(false), undefined
console.log(typeof typeof 1);
"number""string""object""undefined"
const numbers = [1, 2, 3];
numbers[10] = 11;
console.log(numbers);
[1, 2, 3, null x 7, 11][1, 2, 3, 11][1, 2, 3, empty x 7, 11]SyntaxError
(() => {
let x, y;
try {
throw new Error();
} catch (x) {
(x = 1), (y = 2);
console.log(x);
}
console.log(x);
console.log(y);
})();
1 undefined 2undefined undefined undefined1 1 21 undefined undefined
[[0, 1], [2, 3]].reduce(
(acc, cur) => {
return acc.concat(cur);
},
[1, 2],
);
[0, 1, 2, 3, 1, 2][6, 1, 2][1, 2, 0, 1, 2, 3][1, 2, 6]
!!null;
!!'';
!!1;
false true falsefalse false truefalse true truetrue true false
setInterval(() => console.log('Hi'), 1000);
undefined
[...'Lydia'];
["L", "y", "d", "i", "a"]["Lydia"][[], "Lydia"][["L", "y", "d", "i", "a"]]
function* generator(i) {
yield i;
yield i * 2;
}
const gen = generator(10);
console.log(gen.next().value);
console.log(gen.next().value);
[0, 10], [10, 20]20, 2010, 200, 10 and 10, 20
const firstPromise = new Promise((res, rej) => {
setTimeout(res, 500, 'one');
});
const secondPromise = new Promise((res, rej) => {
setTimeout(res, 100, 'two');
});
Promise.race([firstPromise, secondPromise])
.then(res => console.log(res));
"one""two""two" "one""one" "two"
let person = { name: 'Lydia' };
const members = [person];
person = null;
console.log(members);
null[null][{}][{ name: "Lydia" }]
const person = {
name: 'Lydia',
age: 21,
};
for (const item in person) {
console.log(item);
}
{ name: "Lydia" }, { age: 21 }"name", "age""Lydia", 21["name", "Lydia"], ["age", 21]
console.log(3 + 4 + '5');
"345""75"12"12"
const num = parseInt('7*6', 10);
42"42"7NaN
[1, 2, 3].map(num => {
if (typeof num === 'number') return;
return num * 2;
});
[][null, null, null][undefined, undefined, undefined][ 3 x empty ]
function getInfo(member, year) {
member.name = 'Lydia';
year = '1998';
}
const person = { name: 'Sarah' };
const birthYear = '1997';
getInfo(person, birthYear);
console.log(person, birthYear);
{ name: "Lydia" }, "1997"{ name: "Sarah" }, "1998"{ name: "Lydia" }, "1998"{ name: "Sarah" }, "1997"
function greeting() {
throw 'Hello world!';
}
function sayHi() {
try {
const data = greeting();
console.log('It worked!', data);
} catch (e) {
console.log('Oh no an error:', e);
}
}
sayHi();
It worked! Hello world!Oh no an error: undefinedSyntaxError: can only throw Error objectsOh no an error: Hello world!
function Car() {
this.make = 'Lamborghini';
return { make: 'Maserati' };
}
const myCar = new Car();
console.log(myCar.make);
"Lamborghini""Maserati"ReferenceErrorTypeError
(() => {
let x = (y = 10);
})();
console.log(typeof x);
console.log(typeof y);
"undefined", "number""number", "number""object", "number""number", "undefined"
class Dog {
constructor(name) {
this.name = name;
}
}
Dog.prototype.bark = function() {
console.log(`Woof I am ${this.name}`);
};
const pet = new Dog('Mara');
pet.bark();
delete Dog.prototype.bark;
pet.bark();
"Woof I am Mara", TypeError"Woof I am Mara", "Woof I am Mara""Woof I am Mara", undefinedTypeError, TypeError
const set = new Set([1, 1, 2, 3, 4]);
console.log(set);
[1, 1, 2, 3, 4][1, 2, 3, 4]{1, 1, 2, 3, 4}{1, 2, 3, 4}
// counter.js
let counter = 10;
export default counter;
```
```javascript
// index.js
import myCounter from './counter';
myCounter += 1;
console.log(myCounter);
1011ErrorNaN
const name = 'Lydia';
age = 21;
console.log(delete name);
console.log(delete age);
false, true"Lydia", 21true, trueundefined, undefined
const numbers = [1, 2, 3, 4, 5];
const [y] = numbers;
console.log(y);
[[1, 2, 3, 4, 5]][1, 2, 3, 4, 5]1[1]
const user = { name: 'Lydia', age: 21 };
const admin = { admin: true, ...user };
console.log(admin);
{ admin: true, user: { name: "Lydia", age: 21 } }{ admin: true, name: "Lydia", age: 21 }{ admin: true, user: ["Lydia", 21] }{ admin: true }
const person = { name: 'Lydia' };
Object.defineProperty(person, 'age', { value: 21 });
console.log(person);
console.log(Object.keys(person));
{ name: "Lydia", age: 21 }, ["name", "age"]{ name: "Lydia", age: 21 }, ["name"]{ name: "Lydia"}, ["name", "age"]{ name: "Lydia"}, ["age"]
const settings = {
username: 'lydiahallie',
level: 19,
health: 90,
};
const data = JSON.stringify(settings, ['level', 'health']);
console.log(data);
"{"level":19, "health":90}""{"username": "lydiahallie"}""["level", "health"]""{"username": "lydiahallie", "level":19, "health":90}"
let num = 10;
const increaseNumber = () => num++;
const increasePassedNumber = number => number++;
const num1 = increaseNumber();
const num2 = increasePassedNumber(num1);
console.log(num1);
console.log(num2);
10, 1010, 1111, 1111, 12
const value = { number: 10 };
const multiply = (x = { ...value }) => {
console.log((x.number *= 2));
};
multiply();
multiply();
multiply(value);
multiply(value);
20, 40, 80, 16020, 40, 20, 4020, 20, 20, 40NaN, NaN, 20, 40
[1, 2, 3, 4].reduce((x, y) => console.log(x, y));
1 2 and 3 3 and 6 41 2 and 2 3 and 3 41 undefined and 2 undefined and 3 undefined and 4 undefined1 2 and undefined 3 and undefined 4
class Dog {
constructor(name) {
this.name = name;
}
};
class Labrador extends Dog {
// 1
constructor(name, size) {
this.size = size;
}
// 2
constructor(name, size) {
super(name);
this.size = size;
}
// 3
constructor(size) {
super(name);
this.size = size;
}
// 4
constructor(name, size) {
this.name = name;
this.size = size;
}
};
// index.js
console.log('running index.js');
import { sum } from './sum.js';
console.log(sum(1, 2));
// sum.js
console.log('running sum.js');
export const sum = (a, b) => a + b;
running index.js, running sum.js, 3running sum.js, running index.js, 3running sum.js, 3, running index.jsrunning index.js, undefined, running sum.js
console.log(Number(2) === Number(2));
console.log(Boolean(false) === Boolean(false));
console.log(Symbol('foo') === Symbol('foo'));
true, true, falsefalse, true, falsetrue, false, truetrue, true, true
const name = 'Lydia Hallie';
console.log(name.padStart(13));
console.log(name.padStart(2));
"Lydia Hallie", "Lydia Hallie"" Lydia Hallie", " Lydia Hallie" ("[13x whitespace]Lydia Hallie", "[2x whitespace]Lydia Hallie")" Lydia Hallie", "Lydia Hallie" ("[1x whitespace]Lydia Hallie", "Lydia Hallie")"Lydia Hallie", "Lyd",
console.log('🥑' + '💻');
"🥑💻"257548
function* startGame() {
const answer = yield 'Do you love JavaScript?';
if (answer !== 'Yes') {
return "Oh wow... Guess we're done here";
}
return 'JavaScript loves you back ❤️';
}
const game = startGame();
console.log(/* 1 */); // Do you love JavaScript?
console.log(/* 2 */); // JavaScript loves you back ❤️
game.next("Yes").value and game.next().valuegame.next.value("Yes") and game.next.value()game.next().value and game.next("Yes").valuegame.next.value() and game.next.value("Yes")
console.log(String.raw`Hello\nworld`);
Hello world!Hello worldHello\nworldHello\n world
async function getData() {
return await Promise.resolve('I made it!');
}
const data = getData();
console.log(data);
"I made it!"Promise {: "I made it!"} Promise {} undefined
function addToList(item, list) {
return list.push(item);
}
const result = addToList('apple', ['banana']);
console.log(result);
['apple', 'banana']2trueundefined
const box = { x: 10, y: 20 };
Object.freeze(box);
const shape = box;
shape.x = 100;
console.log(shape);
{ x: 100, y: 20 }{ x: 10, y: 20 }{ x: 100 }ReferenceError
const { firstName: myName } = { firstName: 'Lydia' };
console.log(firstName);
"Lydia""myName"undefinedReferenceError
function sum(a, b) {
return a + b;
}
const add = () => {
const cache = {};
return num => {
if (num in cache) {
return `From cache! ${cache[num]}`;
} else {
const result = num + 10;
cache[num] = result;
return `Calculated! ${result}`;
}
};
};
const addFunction = add();
console.log(addFunction(10));
console.log(addFunction(10));
console.log(addFunction(5 * 2));
Calculated! 20 Calculated! 20 Calculated! 20Calculated! 20 From cache! 20 Calculated! 20Calculated! 20 From cache! 20 From cache! 20Calculated! 20 From cache! 20 Error
const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'];
for (let item in myLifeSummedUp) {
console.log(item);
}
for (let item of myLifeSummedUp) {
console.log(item);
}
0 1 2 3 and "☕" "💻" "🍷" "🍫""☕" "💻" "🍷" "🍫" and "☕" "💻" "🍷" "🍫""☕" "💻" "🍷" "🍫" and 0 1 2 30 1 2 3 and {0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}
const list = [1 + 2, 1 * 2, 1 / 2];
console.log(list);
["1 + 2", "1 * 2", "1 / 2"]["12", 2, 0.5][3, 2, 0.5][1, 1, 1]
function sayHi(name) {
return `Hi there, ${name}`;
}
console.log(sayHi());
Hi there,Hi there, undefinedHi there, nullReferenceError
var status = '😎';
setTimeout(() => {
const status = '😍';
const data = {
status: '🥑',
getStatus() {
return this.status;
},
};
console.log(data.getStatus());
console.log(data.getStatus.call(this));
}, 0);
"🥑" and "😍""🥑" and "😎""😍" and "😎""😎" and "😎"
const person = {
name: 'Lydia',
age: 21,
};
let city = person.city;
city = 'Amsterdam';
console.log(person);
{ name: "Lydia", age: 21 }{ name: "Lydia", age: 21, city: "Amsterdam" }{ name: "Lydia", age: 21, city: undefined }"Amsterdam"
function checkAge(age) {
if (age < 18) {
const message = "Sorry, you're too young.";
} else {
const message = "Yay! You're old enough!";
}
return message;
}
console.log(checkAge(21));
"Sorry, you're too young.""Yay! You're old enough!"ReferenceErrorundefined
fetch('https://www.website.com/api/user/1')
.then(res => res.json())
.then(res => console.log(res));
fetch method.fetch method..then().
function getName(name) {
const hasName = //
}
!!namenamenew Boolean(name)name.length
console.log('I want pizza'[0]);
""""I"SyntaxErrorundefined
function sum(num1, num2 = num1) {
console.log(num1 + num2);
}
sum(10);
NaN20ReferenceErrorundefined
// module.js
export default () => 'Hello world';
export const name = 'Lydia';
// index.js
import * as data from './module';
console.log(data);
{ default: function default(), name: "Lydia" }{ default: function default() }{ default: "Hello world", name: "Lydia" }module.js
class Person {
constructor(name) {
this.name = name;
}
}
const member = new Person('John');
console.log(typeof member);
"class""function""object""string"
let newList = [1, 2, 3].push(4);
console.log(newList.push(5));
[1, 2, 3, 4, 5][1, 2, 3, 5][1, 2, 3, 4]Error
function giveLydiaPizza() {
return 'Here is pizza!';
}
const giveLydiaChocolate = () =>
"Here's chocolate... now go hit the gym already.";
console.log(giveLydiaPizza.prototype);
console.log(giveLydiaChocolate.prototype);
{ constructor: ...} { constructor: ...}{} { constructor: ...}{ constructor: ...} {}{ constructor: ...} undefined
const person = {
name: 'Lydia',
age: 21,
};
for (const [x, y] of Object.entries(person)) {
console.log(x, y);
}
name Lydia and age 21["name", "Lydia"] and ["age", 21]["name", "age"] and undefinedError
function getItems(fruitList, ...args, favoriteFruit) {
return [...fruitList, ...args, favoriteFruit]
}
getItems(["banana", "apple"], "pear", "orange")
["banana", "apple", "pear", "orange"][["banana", "apple"], "pear", "orange"]["banana", "apple", ["pear"], "orange"]SyntaxError
function nums(a, b) {
if (a > b) console.log('a is bigger');
else console.log('b is bigger');
return
a + b;
}
console.log(nums(4, 2));
console.log(nums(1, 2));
a is bigger, 6 and b is bigger, 3a is bigger, undefined and b is bigger, undefinedundefined and undefinedSyntaxError
class Person {
constructor() {
this.name = 'Lydia';
}
}
Person = class AnotherPerson {
constructor() {
this.name = 'Sarah';
}
};
const member = new Person();
console.log(member.name);
"Lydia""Sarah"Error: cannot redeclare PersonSyntaxError
const info = {
[Symbol('a')]: 'b',
};
console.log(info);
console.log(Object.keys(info));
{Symbol('a'): 'b'} and ["{Symbol('a')"]{} and []{ a: "b" } and ["a"]{Symbol('a'): 'b'} and []
const getList = ([x, ...y]) => [x, y]
const getUser = user => { name: user.name, age: user.age }
const list = [1, 2, 3, 4]
const user = { name: "Lydia", age: 21 }
console.log(getList(list))
console.log(getUser(user))
[1, [2, 3, 4]] and SyntaxError[1, [2, 3, 4]] and { name: "Lydia", age: 21 }[1, 2, 3, 4] and { name: "Lydia", age: 21 }Error and { name: "Lydia", age: 21 }
const name = 'Lydia';
console.log(name());
SyntaxErrorReferenceErrorTypeErrorundefined
// 🎉✨ This is my 100th question! ✨🎉
const output = `${[] && 'Im'}possible!
You should${'' && `n't`} see a therapist after so much JavaScript lol`;
possible! You should see a therapist after so much JavaScript lolImpossible! You should see a therapist after so much JavaScript lolpossible! You shouldn't see a therapist after so much JavaScript lolImpossible! You shouldn't see a therapist after so much JavaScript lol
const one = false || {} || null;
const two = null || false || '';
const three = [] || 0 || true;
console.log(one, two, three);
false null []null "" true{} "" []null null true
const myPromise = () => Promise.resolve('I have resolved!');
function firstFunction() {
myPromise().then(res => console.log(res));
console.log('second');
}
async function secondFunction() {
console.log(await myPromise());
console.log('second');
}
firstFunction();
secondFunction();
I have resolved!, second and I have resolved!, secondsecond, I have resolved! and second, I have resolved!I have resolved!, second and second, I have resolved!second, I have resolved! and I have resolved!, second
const set = new Set();
set.add(1);
set.add('Lydia');
set.add({ name: 'Lydia' });
for (let item of set) {
console.log(item + 2);
}
3, NaN, NaN3, 7, NaN3, Lydia2, [object Object]2"12", Lydia2, [object Object]2
Promise.resolve(5);
5Promise {: 5} Promise {: 5} Error
function compareMembers(person1, person2 = person) {
if (person1 !== person2) {
console.log('Not the same!');
} else {
console.log('They are the same!');
}
}
const person = { name: 'Lydia' };
compareMembers(person);
Not the same!They are the same!ReferenceErrorSyntaxError
const colorConfig = {
red: true,
blue: false,
green: true,
black: true,
yellow: false,
};
const colors = ['pink', 'red', 'blue'];
console.log(colorConfig.colors[1]);
truefalseundefinedTypeError
console.log('❤️' === '❤️');
truefalse
const emojis = ['✨', '🥑', '😍'];
emojis.map(x => x + '✨');
emojis.filter(x => x !== '🥑');
emojis.find(x => x !== '🥑');
emojis.reduce((acc, cur) => acc + '✨');
emojis.slice(1, 2, '✨');
emojis.splice(1, 2, '✨');
All of themmap reduce slice splicemap slice splicesplice
const food = ['🍕', '🍫', '🥑', '🍔'];
const info = { favoriteFood: food[0] };
info.favoriteFood = '🍝';
console.log(food);
['🍕', '🍫', '🥑', '🍔']['🍝', '🍫', '🥑', '🍔']['🍝', '🍕', '🍫', '🥑', '🍔']ReferenceError
JSON.parse();
let name = 'Lydia';
function getName() {
console.log(name);
let name = 'Sarah';
}
getName();
undefinedReferenceError
function* generatorOne() {
yield ['a', 'b', 'c'];
}
function* generatorTwo() {
yield* ['a', 'b', 'c'];
}
const one = generatorOne();
const two = generatorTwo();
console.log(one.next().value);
console.log(two.next().value);
a and aa and undefined['a', 'b', 'c'] and aa and ['a', 'b', 'c']
console.log(`${(x => x)('I love')} to program`);
I love to programundefined to program${(x => x)('I love') to programTypeError
let config = {
alert: setInterval(() => {
console.log('Alert!');
}, 1000),
};
config = null;
setInterval callback won't be invokedsetInterval callback gets invoked oncesetInterval callback will still be called every secondconfig.alert(), config is null
const myMap = new Map();
const myFunc = () => 'greeting';
myMap.set(myFunc, 'Hello world!');
//1
myMap.get('greeting');
//2
myMap.get(myFunc);
//3
myMap.get(() => 'greeting');
const person = {
name: 'Lydia',
age: 21,
};
const changeAge = (x = { ...person }) => (x.age += 1);
const changeAgeAndName = (x = { ...person }) => {
x.age += 1;
x.name = 'Sarah';
};
changeAge(person);
changeAgeAndName();
console.log(person);
{name: "Sarah", age: 22}{name: "Sarah", age: 23}{name: "Lydia", age: 22}{name: "Lydia", age: 23}
function sumValues(x, y, z) {
return x + y + z;
}
sumValues([...1, 2, 3])sumValues([...[1, 2, 3]])sumValues(...[1, 2, 3])sumValues([1, 2, 3])
let num = 1;
const list = ['🥳', '🤠', '🥰', '🤪'];
console.log(list[(num += 1)]);
🤠🥰SyntaxErrorReferenceError
const person = {
firstName: 'Lydia',
lastName: 'Hallie',
pet: {
name: 'Mara',
breed: 'Dutch Tulip Hound',
},
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(person.pet?.name);
console.log(person.pet?.family?.name);
console.log(person.getFullName?.());
console.log(member.getLastName?.());
undefined undefined undefined undefinedMara undefined Lydia Hallie ReferenceErrorMara null Lydia Hallie nullnull ReferenceError null ReferenceError
const groceries = ['banana', 'apple', 'peanuts'];
if (groceries.indexOf('banana')) {
console.log('We have to buy bananas!');
} else {
console.log(`We don't have to buy bananas!`);
}
undefined1
const config = {
languages: [],
set language(lang) {
return this.languages.push(lang);
},
};
console.log(config.language);
function language(lang) { this.languages.push(lang }0[]undefined
const name = 'Lydia Hallie';
console.log(!typeof name === 'object');
console.log(!typeof name === 'string');
false truetrue falsefalse falsetrue true
const add = x => y => z => {
console.log(x, y, z);
return x + y + z;
};
add(4)(5)(6);
4 5 66 5 44 function functionundefined undefined 6
async function* range(start, end) {
for (let i = start; i <= end; i++) {
yield Promise.resolve(i);
}
}
(async () => {
const gen = range(1, 3);
for await (const item of gen) {
console.log(item);
}
})();
Promise {1} Promise {2} Promise {3}Promise {} Promise {} Promise {} 1 2 3undefined undefined undefined
const myFunc = ({ x, y, z }) => {
console.log(x, y, z);
};
myFunc(1, 2, 3);
1 2 3{1: 1} {2: 2} {3: 3}{ 1: undefined } undefined undefinedundefined undefined undefined
function getFine(speed, amount) {
const formattedSpeed = new Intl.NumberFormat('en-US', {
style: 'unit',
unit: 'mile-per-hour'
}).format(speed);
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(amount);
return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`;
}
console.log(getFine(130, 300))
const spookyItems = ['👻', '🎃', '🕸'];
({ item: spookyItems[3] } = { item: '💀' });
console.log(spookyItems);
["👻", "🎃", "🕸"]["👻", "🎃", "🕸", "💀"]["👻", "🎃", "🕸", { item: "💀" }]["👻", "🎃", "🕸", "[object Object]"]
const name = 'Lydia Hallie';
const age = 21;
console.log(Number.isNaN(name));
console.log(Number.isNaN(age));
console.log(isNaN(name));
console.log(isNaN(age));
true false true falsetrue false false falsefalse false true falsefalse true false true
const randomValue = 21;
function getInfo() {
console.log(typeof randomValue);
const randomValue = 'Lydia Hallie';
}
getInfo();
"number""string"undefinedReferenceError
const myPromise = Promise.resolve('Woah some cool data');
(async () => {
try {
console.log(await myPromise);
} catch {
throw new Error(`Oops didn't work`);
} finally {
console.log('Oh finally!');
}
})();
Woah some cool dataOh finally!Woah some cool data Oh finally!Oops didn't work Oh finally!
const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]];
console.log(emojis.flat(1));
['🥑', ['✨', '✨', ['🍕', '🍕']]]['🥑', '✨', '✨', ['🍕', '🍕']]['🥑', ['✨', '✨', '🍕', '🍕']]['🥑', '✨', '✨', '🍕', '🍕']
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counterOne = new Counter();
counterOne.increment();
counterOne.increment();
const counterTwo = counterOne;
counterTwo.increment();
console.log(counterOne.count);
0123
const myPromise = Promise.resolve(Promise.resolve('Promise'));
function funcOne() {
setTimeout(() => console.log('Timeout 1!'), 0);
myPromise.then(res => res).then(res => console.log(`${res} 1!`));
console.log('Last line 1!');
}
async function funcTwo() {
const res = await myPromise;
console.log(`${res} 2!`)
setTimeout(() => console.log('Timeout 2!'), 0);
console.log('Last line 2!');
}
funcOne();
funcTwo();
Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!
// sum.js
export default function sum(x) {
return x + x;
}
// index.js
import * as sum from './sum';
sum(4)sum.sum(4)sum.default(4)*, only named exports
const handler = {
set: () => console.log('Added a new property!'),
get: () => console.log('Accessed a property!'),
};
const person = new Proxy({}, handler);
person.name = 'Lydia';
person.name;
Added a new property!Accessed a property!Added a new property! Accessed a property!
const person = { name: 'Lydia Hallie' };
Object.seal(person);
person.name = "Evan Bacon"person.age = 21delete person.nameObject.assign(person, { age: 21 })
const person = {
name: 'Lydia Hallie',
address: {
street: '100 Main St',
},
};
Object.freeze(person);
person.name = "Evan Bacon"delete person.addressperson.address.street = "101 Main St"person.pet = { name: "Mara" }
const add = x => x + x;
function myFunc(num = 2, value = add(num)) {
console.log(num, value);
}
myFunc();
myFunc(3);
2 4 and 3 62 NaN and 3 NaN2 Error and 3 62 4 and 3 Error
class Counter {
#number = 10
increment() {
this.#number++
}
getNum() {
return this.#number
}
}
const counter = new Counter()
counter.increment()
console.log(counter.#number)
1011undefinedSyntaxError
const teams = [
{ name: 'Team 1', members: ['Paul', 'Lisa'] },
{ name: 'Team 2', members: ['Laura', 'Tim'] },
];
function* getMembers(members) {
for (let i = 0; i < members.length; i++) {
yield members[i];
}
}
function* getTeams(teams) {
for (let i = 0; i < teams.length; i++) {
// ✨ SOMETHING IS MISSING HERE ✨
}
}
const obj = getTeams(teams);
obj.next(); // { value: "Paul", done: false }
obj.next(); // { value: "Lisa", done: false }
yield getMembers(teams[i].members)yield* getMembers(teams[i].members)return getMembers(teams[i].members)return yield getMembers(teams[i].members)
const person = {
name: 'Lydia Hallie',
hobbies: ['coding'],
};
function addHobby(hobby, hobbies = person.hobbies) {
hobbies.push(hobby);
return hobbies;
}
addHobby('running', []);
addHobby('dancing');
addHobby('baking', person.hobbies);
console.log(person.hobbies);
["coding"]["coding", "dancing"]["coding", "dancing", "baking"]["coding", "running", "dancing", "baking"]
class Bird {
constructor() {
console.log("I'm a bird. 🦢");
}
}
class Flamingo extends Bird {
constructor() {
console.log("I'm pink. 🌸");
super();
}
}
const pet = new Flamingo();
I'm pink. 🌸I'm pink. 🌸 I'm a bird. 🦢I'm a bird. 🦢 I'm pink. 🌸
const emojis = ['🎄', '🎅🏼', '🎁', '⭐'];
/* 1 */ emojis.push('🦌');
/* 2 */ emojis.splice(0, 2);
/* 3 */ emojis = [...emojis, '🥂'];
/* 4 */ emojis.length = 0;
const person = {
name: "Lydia Hallie",
age: 21
}
[...person] // ["Lydia Hallie", 21]
*[Symbol.iterator]() { for (let x in this) yield* this[x] }*[Symbol.iterator]() { yield* Object.values(this) }*[Symbol.iterator]() { for (let x in this) yield this }
let count = 0;
const nums = [0, 1, 2, 3];
nums.forEach(num => {
if (num) count += 1
})
console.log(count)
function getFruit(fruits) {
console.log(fruits?.[1]?.[1])
}
getFruit([['🍊', '🍌'], ['🍍']])
getFruit()
getFruit([['🍍'], ['🍊', '🍌']])
null, undefined, 🍌[], null, 🍌[], [], 🍌undefined, undefined, 🍌
class Calc {
constructor() {
this.count = 0
}
increase() {
this.count ++
}
}
const calc = new Calc()
new Calc().increase()
console.log(calc.count)
01undefinedReferenceError
const user = {
email: "e@mail.com",
password: "12345"
}
const updateUser = ({ email, password }) => {
if (email) {
Object.assign(user, { email })
}
if (password) {
user.password = password
}
return user
}
const updatedUser = updateUser({ email: "new@email.com" })
console.log(updatedUser === user)
falsetrueTypeErrorReferenceError
const fruit = ['🍌', '🍊', '🍎']
fruit.slice(0, 1)
fruit.splice(0, 1)
fruit.unshift('🍇')
console.log(fruit)
['🍌', '🍊', '🍎']['🍊', '🍎']['🍇', '🍊', '🍎']['🍇', '🍌', '🍊', '🍎']
const animals = {};
let dog = { emoji: '🐶' }
let cat = { emoji: '🐈' }
animals[dog] = { ...dog, name: "Mara" }
animals[cat] = { ...cat, name: "Sara" }
console.log(animals[dog])
{ emoji: "🐶", name: "Mara" }{ emoji: "🐈", name: "Sara" }undefinedReferenceError
const user = {
email: "my@email.com",
updateEmail: email => {
this.email = email
}
}
user.updateEmail("new@email.com")
console.log(user.email)
my@email.comnew@email.comundefinedReferenceError
const promise1 = Promise.resolve('First')
const promise2 = Promise.resolve('Second')
const promise3 = Promise.reject('Third')
const promise4 = Promise.resolve('Fourth')
const runPromises = async () => {
const res1 = await Promise.all([promise1, promise2])
const res2 = await Promise.all([promise3, promise4])
return [res1, res2]
}
runPromises()
.then(res => console.log(res))
.catch(err => console.log(err))
[['First', 'Second'], ['Fourth']][['First', 'Second'], ['Third', 'Fourth']][['First', 'Second']]'Third'
const keys = ["name", "age"]
const values = ["Lydia", 22]
const method = /* ?? */
Object[method](keys.map((_, i) => {
return [keys[i], values[i]]
})) // { name: "Lydia", age: 22 }
entriesvaluesfromEntriesforEach
const createMember = ({ email, address = {}}) => {
const validEmail = /.+\@.+\..+/.test(email)
if (!validEmail) throw new Error("Valid email pls")
return {
email,
address: address ? address : null
}
}
const member = createMember({ email: "my@email.com" })
console.log(member)
{ email: "my@email.com", address: null }{ email: "my@email.com" }{ email: "my@email.com", address: {} }{ email: "my@email.com", address: undefined }
let randomValue = { name: "Lydia" }
randomValue = 23
if (!typeof randomValue === "string") {
console.log("It's not a string!")
} else {
console.log("Yay it's a string!")
}
It's not a string!Yay it's a string!TypeErrorundefined