JavaScript: undefined
It's possible to declare variable without giving it a specific value. What will be printed in this case?
let name;
console.log(name); // ?undefined is a special value of its own type that denotes an absence of value. Undefined is used by JavaScript in many different cases, for example when calling a non-existent string character:
const name = 'Arya';
console.log(name[8]);The meaning (semantics) of undefined is an absence of value. However, nothing stops you from writing the following code:
let key = undefined;Although the interpreter allows this, it violates the semantics of undefined, because this code performs an assignment and therefore substitutes a value.
JavaScript is one of the few languages that explicitly includes undefined. Other languages use null instead of undefined, and JavaScript uses null too.
Self-check. Why can't we declare a constant without specifying a value?
Instructions
Print the undefined value without explicitly specifying it (by assignment or by putting it directly into console.log()). If you can't figure out how to do it, look up the teacher's solution.
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('undefined', async () => {
const consoleLogSpy = vi.spyOn(console, 'log');
await import('./index.js');
// console.log must be called and must be passed an undefined argument
expect(consoleLogSpy).toHaveBeenCalled();
const [firstCall] = consoleLogSpy.mock.calls;
expect(firstCall?.length).toBeGreaterThan(0);
expect(firstCall?.[0]).toBe(undefined);
});Teacher's solution will be available in:
20:00
