1. What prints to the console?
function show() {
console.log(firstName);
console.log(lastName);
var firstName = "Ari";
let lastName = "Khan";
}
show();JavaScript Interview Practice
Click an option to reveal the correct answer and a short explanation.
function show() {
console.log(firstName);
console.log(lastName);
var firstName = "Ari";
let lastName = "Khan";
}
show();for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var", i), 1);
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log("let", i), 1);
}const ring = {
r: 5,
diameter() {
return this.r * 2;
},
circumference: () => 2 * Math.PI * this.r,
};
console.log(ring.diameter());
console.log(ring.circumference());+false;
!"hello";const key = { size: "tiny" };
const item = { name: "mouse", tiny: true };let obj1 = { msg: "Hi" };
let obj2;
obj2 = obj1;
obj1.msg = "Hey";
console.log(obj2.msg);let a = 4;
let b = new Number(4);
let c = 4;
console.log(a == b);
console.log(a === b);
console.log(b === c);class Gecko {
static paint(newColor) {
this.color = newColor;
return this.color;
}
}
const gary = new Gecko();
console.log(gary.paint("orange"));"use strict";
let title;
titl = {}; // typo
console.log(titl);function bark() {
console.log("Woof!");
}
bark.kind = "dog";function Person(first, last) {
this.first = first;
this.last = last;
}
const member = new Person("Ari", "Khan");
Person.fullName = function () {
return this.first + " " + this.last;
};
console.log(member.fullName());"use strict";
function Person(first, last) {
this.first = first;
this.last = last;
}
const ari = new Person("Ari", "Khan");
const sam = Person("Sam", "Lee");
console.log(ari);
console.log(sam);function sum(a, b) {
return a + b;
}
sum(1, "2");let n = 0;
console.log(n++);
console.log(++n);
console.log(n);function info(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
const person = "Mia";
const age = 30;
info`${person} is ${age} years old`;function checkAge(data) {
if (data === { age: 18 }) {
console.log("Adult");
} else if (data == { age: 18 }) {
console.log("Still adult");
} else {
console.log("No age");
}
}
checkAge({ age: 18 });function getAge(...args) {
console.log(typeof args);
}
getAge(21);function getAge() {
"use strict";
age = 21;
console.log(age);
}
getAge();const total = eval("10*10+5");sessionStorage.setItem("token", "abc");var num = 8;
var num = 10;
console.log(num);const obj = { 1: "a", 2: "b" };
const set = new Set([1, 2, 3]);
obj.hasOwnProperty("1");
obj.hasOwnProperty(1);
set.has("1");
set.has(1);const obj = { a: "one", b: "two", a: "three" };
console.log(obj);for (let i = 1; i < 5; i++) {
if (i === 3) continue;
console.log(i);
}String.prototype.sayPizza = () => "Pizza time!";
const name = "Noah";
console.log(name.sayPizza());const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);const first = () => console.log("First");
const second = () => setTimeout(() => console.log("Second"));
const third = () => console.log("Third");
second();
first();
third();<div onclick="console.log('outer')">
<div onclick="console.log('inner')">
<button onclick="console.log('button')">Click</button>
</div>
</div><div onclick="console.log('div')">
<p onclick="console.log('p')">Tap</p>
</div>const person = { name: "Noah" };
function sayHi(age) {
return this.name + " is " + age;
}
console.log(sayHi.call(person, 21));
console.log(sayHi.bind(person, 21));function sayHi() {
return (() => 0)();
}
console.log(typeof sayHi());0;
new Number(0);
("");
(" ");
new Boolean(false);
undefined;console.log(typeof typeof 1);const nums = [1, 2, 3];
nums[10] = 11;
console.log(nums);(() => {
let x, y;
try {
throw new Error("oops");
} catch (x) {
(x = 1), (y = 2);
console.log(x);
}
console.log(x);
console.log(y);
})();[[0, 1], [2, 3]].reduce(
(acc, cur) => acc.concat(cur),
[1, 2]
);!!null;
!!"";
!!1;setInterval(() => console.log("Hi"), 1000);[..."Maya"];function* gen(i) {
yield i;
yield i * 2;
}
const g = gen(6);
console.log(g.next().value);
console.log(g.next().value);const first = new Promise((res) => setTimeout(res, 400, "first"));
const second = new Promise((res) => setTimeout(res, 50, "second"));
Promise.race([first, second]).then((v) => console.log(v));let person = { name: "Ari" };
const members = [person];
person = null;
console.log(members);const person = { name: "Ari", age: 21 };
for (const key in person) {
console.log(key);
}console.log(3 + 4 + "5");const value = parseInt("7*6", 10);[1, 2, 3].map((n) => {
if (typeof n === "number") return;
return n * 2;
});function update(person, year) {
person.name = "Kai";
year = "2000";
}
const person = { name: "Zoe" };
const birthYear = "1999";
update(person, birthYear);
console.log(person, birthYear);function boom() {
throw "Boom!";
}
function test() {
try {
boom();
console.log("ok");
} catch (e) {
console.log("caught:", e);
}
}
test();function Car() {
this.make = "Tesla";
return { make: "Volvo" };
}
const car = new Car();
console.log(car.make);(() => {
let x = (y = 10);
})();
console.log(typeof x);
console.log(typeof y);class Dog {
constructor(name) {
this.name = name;
}
}
Dog.prototype.bark = function () {
console.log("Woof " + this.name);
};
const pet = new Dog("Rex");
pet.bark();
delete Dog.prototype.bark;
pet.bark();const set = new Set([1, 1, 2, 3, 4]);
console.log(set);// counter.js
let count = 10;
export default count;
// index.js
import counter from "./counter";
counter += 1;
console.log(counter);var name = "Ari";
age = 21;
console.log(delete name);
console.log(delete age);const numbers = [1, 2, 3, 4, 5];
const [x] = numbers;
console.log(x);const user = { name: "Ari", age: 22 };
const admin = { admin: true, ...user };
console.log(admin);const person = { name: "Ari" };
Object.defineProperty(person, "age", { value: 22 });
console.log(person);
console.log(Object.keys(person));const settings = { user: "neo", level: 3, health: 90 };
const data = JSON.stringify(settings, ["level", "health"]);
console.log(data);let num = 10;
const inc = () => num++;
const incCopy = (n) => n++;
const a = inc();
const b = incCopy(a);
console.log(a);
console.log(b);const value = { number: 10 };
const multiply = (x = { ...value }) => {
console.log((x.number *= 2));
};
multiply();
multiply();
multiply(value);
multiply(value);[1, 2, 3, 4].reduce((x, y) => console.log(x, y));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("index");
import { sum } from "./sum.js";
console.log(sum(1, 2));
// sum.js
console.log("sum");
export const sum = (a, b) => a + b;console.log(Number(2) === Number(2));
console.log(Boolean(false) === Boolean(false));
console.log(Symbol("x") === Symbol("x"));const name = "Nova";
console.log(name.padStart(6));
console.log(name.padStart(2));console.log("foo" + "bar");function* startGame() {
const answer = yield "Do you like JS?";
if (answer !== "Yes") return "Game over";
return "You are awesome";
}
const game = startGame();
console.log(/* 1 */); // Do you like JS?
console.log(/* 2 */); // You are awesomeconsole.log(String.raw`Hello\nworld`);async function getData() {
return await Promise.resolve("Done!");
}
const data = getData();
console.log(data);function addToList(item, list) {
return list.push(item);
}
const result = addToList("apple", ["banana"]);
console.log(result);const box = { x: 10, y: 20 };
Object.freeze(box);
const shape = box;
shape.x = 100;
console.log(shape);const { firstName: alias } = { firstName: "Ari" };
console.log(firstName);function sum(a, b) {
return a + b;
}const add = () => {
const cache = {};
return (num) => {
if (num in cache) return "From cache! " + cache[num];
const result = num + 10;
cache[num] = result;
return "Calculated! " + result;
};
};
const fn = add();
console.log(fn(10));
console.log(fn(10));
console.log(fn(5 * 2));const life = ["coffee", "code", "pizza"];
for (let i in life) console.log(i);
for (let v of life) console.log(v);const list = [1 + 2, 1 * 2, 1 / 2];
console.log(list);function sayHi(name) {
return "Hi, " + name;
}
console.log(sayHi());var mood = "cool";
setTimeout(function () {
const mood = "warm";
const data = {
mood: "fresh",
getMood() {
return this.mood;
},
};
console.log(data.getMood());
console.log(data.getMood.call({ mood: "ok" }));
}, 0);const person = { name: "Ari", age: 21 };
let city = person.city;
city = "Oslo";
console.log(person);function checkAge(age) {
if (age < 18) {
const msg = "Too young";
} else {
const msg = "Old enough";
}
return msg;
}
console.log(checkAge(21));fetch("https://example.com/api/user/1")
.then((res) => res.json())
.then((data) => console.log(data));function getName(name) {
const hasName = // ?
}console.log("I want pizza"[0]);function sum(a, b = a) {
console.log(a + b);
}
sum(10);// module.js
export default () => "Hello";
export const name = "Ari";
// index.js
import * as data from "./module";
console.log(data);class Person {
constructor(name) {
this.name = name;
}
}
const member = new Person("John");
console.log(typeof member);let list = [1, 2, 3].push(4);
console.log(list.push(5));function givePizza() {
return "Pizza!";
}
const giveChoco = () => "Chocolate!";
console.log(givePizza.prototype);
console.log(giveChoco.prototype);const person = { name: "Ari", age: 21 };
for (const [k, v] of Object.entries(person)) {
console.log(k, v);
}function getItems(list, ...rest, last) {
return [...list, ...rest, last];
}
getItems(["a", "b"], "c", "d");function nums(a, b) {
if (a > b) console.log("a bigger");
else console.log("b bigger");
return
a + b;
}
console.log(nums(4, 2));
console.log(nums(1, 2));class Person {
constructor() {
this.name = "Ari";
}
}
Person = class AnotherPerson {
constructor() {
this.name = "Sam";
}
};
const member = new Person();
console.log(member.name);const info = { [Symbol("x")]: "y" };
console.log(info);
console.log(Object.keys(info));const getList = ([x, ...y]) => [x, y];
const getUser = (user) => { name: user.name, age: user.age };
const list = [1, 2, 3, 4];
const user = { name: "Ari", age: 21 };
console.log(getList(list));
console.log(getUser(user));const name = "Ari";
console.log(name());const output = `${[] && "Not"}possible!
You should${"" && "n't"} worry`;const one = false || {} || null;
const two = null || false || "";
const three = [] || 0 || true;
console.log(one, two, three);const wait = () => new Promise((res) => setTimeout(() => res("done"), 0));
function first() {
wait().then((v) => console.log("first:", v));
console.log("first: sync");
}
async function second() {
console.log("second:", await wait());
console.log("second: sync");
}
first();
second();const set = new Set();
set.add(1);
set.add("Ari");
set.add({ name: "Ari" });
for (let item of set) {
console.log(item + 2);
}Promise.resolve(5);function compare(a, b = person) {
if (a !== b) console.log("Different");
else console.log("Same");
}
const person = { name: "Ari" };
compare(person);const config = {
red: true,
blue: false,
green: true,
};
const colors = ["pink", "red", "blue"];
console.log(config.colors?.[1]);console.log("hi" === "hi");const items = ["spark", "leaf", "smile"];
items.map((x) => x + "x");
items.filter((x) => x !== "leaf");
items.find((x) => x !== "leaf");
items.reduce((acc, cur) => acc + "x", "");
items.slice(1, 2, "x");
items.splice(1, 2, "x");const menu = ["pizza", "chocolate", "avocado", "burger"];
const info = { favorite: menu[0] };
info.favorite = "pasta";
console.log(menu);let name = "Nora";
function getName() {
console.log(name);
let name = "Sasha";
}
getName();function* genOne() {
yield ["a", "b", "c"];
}
function* genTwo() {
yield* ["a", "b", "c"];
}
const one = genOne();
const two = genTwo();
console.log(one.next().value);
console.log(two.next().value);console.log(`${(x => x)("I enjoy")} to code`);let config = {
timer: setInterval(() => {
console.log("Tick");
}, 1000),
};
config = 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: "Nora", age: 20 };
const changeAge = (x = { ...person }) => (x.age += 1);
const changeAgeAndName = (x = { ...person }) => {
x.age += 1;
x.name = "Sara";
};
changeAge(person);
changeAgeAndName();
console.log(person);function sumValues(x, y, z) {
return x + y + z;
}
let num = 1;
const list = ["party", "hat", "smile", "wild"];
console.log(list[(num += 1)]);const person = {
firstName: "Nora",
lastName: "Hill",
pet: {
name: "Milo",
breed: "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?.());const groceries = ["banana", "apple", "peanuts"];
if (groceries.indexOf("banana")) {
console.log("We should buy bananas");
} else {
console.log("No bananas needed");
}const config = {
languages: [],
set language(lang) {
return this.languages.push(lang);
},
};
console.log(config.language);const name = "Nora Hill";
console.log(!typeof name === "object");
console.log(!typeof name === "string");const add = x => y => z => {
console.log(x, y, z);
return x + y + z;
};
add(4)(5)(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);
}
})();const myFunc = ({ x, y, z }) => {
console.log(x, y, z);
};
myFunc(1, 2, 3);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 spooky = ["ghost", "pumpkin", "web"];
({ item: spooky[3] } = { item: "skull" });
console.log(spooky);const name = "Nora Hill";
const age = 21;
console.log(Number.isNaN(name));
console.log(Number.isNaN(age));
console.log(isNaN(name));
console.log(isNaN(age));const randomValue = 21;
function getInfo() {
console.log(typeof randomValue);
const randomValue = "Nora Hill";
}
getInfo();const myPromise = Promise.resolve("Great data");
(async () => {
try {
console.log(await myPromise);
} catch {
throw new Error("Oops");
} finally {
console.log("Finally!");
}
})();const items = ["a", ["b", "b", ["c", "c"]]];
console.log(items.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);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();// sum.js
export default function sum(x) {
return x + x;
}
// index.js
import * as sum from "./sum";const handler = {
set: () => console.log("Added a new property!"),
get: () => console.log("Accessed a property!"),
};
const person = new Proxy({}, handler);
person.name = "Nora";
person.name;const person = { name: "Nora Hill" };
Object.seal(person);const person = {
name: "Nora Hill",
address: {
street: "100 Main St",
},
};
Object.freeze(person);const add = (x) => x + x;
function myFunc(num = 2, value = add(num)) {
console.log(num, value);
}
myFunc();
myFunc(3);class Counter {
#number = 10;
increment() {
this.#number++;
}
getNum() {
return this.#number;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.#number);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++) {
// missing
}
}
const obj = getTeams(teams);
obj.next();
obj.next();const person = {
name: "Nora Hill",
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);class Bird {
constructor() {
console.log("I'm a bird.");
}
}
class Flamingo extends Bird {
constructor() {
console.log("I'm pink.");
super();
}
}
const pet = new Flamingo();const items = ["tree", "santa", "gift", "star"];
/* 1 */ items.push("reindeer");
/* 2 */ items.splice(0, 2);
/* 3 */ items = [...items, "toast"];
/* 4 */ items.length = 0;const person = {
name: "Nora Hill",
age: 21,
};
[...person];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([["orange", "banana"], ["pineapple"]]);
getFruit();
getFruit([["pineapple"], ["orange", "banana"]]);class Calc {
constructor() {
this.count = 0;
}
increase() {
this.count++;
}
}
const calc = new Calc();
new Calc().increase();
console.log(calc.count);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@mail.com" });
console.log(updatedUser === user);const fruit = ["banana", "orange", "apple"];
fruit.slice(0, 1);
fruit.splice(0, 1);
fruit.unshift("grape");
console.log(fruit);const animals = {};
let dog = { emoji: "dog" };
let cat = { emoji: "cat" };
animals[dog] = { ...dog, name: "Mara" };
animals[cat] = { ...cat, name: "Sara" };
console.log(animals[dog]);const user = {
email: "my@mail.com",
updateEmail: (email) => {
this.email = email;
},
};
user.updateEmail("new@mail.com");
console.log(user.email);const p1 = Promise.resolve("First");
const p2 = Promise.resolve("Second");
const p3 = Promise.reject("Third");
const p4 = Promise.resolve("Fourth");
const runPromises = async () => {
const res1 = await Promise.all([p1, p2]);
const res2 = await Promise.all([p3, p4]);
return [res1, res2];
};
runPromises()
.then((res) => console.log(res))
.catch((err) => console.log(err));const keys = ["name", "age"];
const values = ["Nora", 22];
const method = /* ?? */;
Object[method](keys.map((_, i) => [keys[i], values[i]]));const createMember = ({ email, address = {} }) => {
const valid = /.+@.+..+/.test(email);
if (!valid) throw new Error("Valid email pls");
return {
email,
address: address ? address : null,
};
};
const member = createMember({ email: "my@mail.com" });
console.log(member);let randomValue = { name: "Nora" };
randomValue = 23;
if (!typeof randomValue === "string") {
console.log("It's not a string!");
} else {
console.log("Yay it's a string!");
}