JavaScript

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/9

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No study sessions yet.

10 Terms

1
New cards

Типы данных в JavaScript?

В JavaScript есть 8 основных типов данных. Их можно разделить на две группы: примитивы (простые значения) и объекты (сложные структуры).

1. Примитивные типы (простые)

Они содержат только одно значение и неизменяемы.

  • Number: Любые числа (целые и дробные).

    • Пример: let age = 25;

  • BigInt: Для очень больших целых чисел, которые не влезают в Number.

    • Пример: let bigNumber = 9007199254740991n;

  • String: Строки (текст).

    • Пример: let name = "Ivan";

  • Boolean: Логический тип, только два значения.

    • Пример: let isHappy = true;

  • undefined: Значение не присвоено. Если вы создали переменную, но ничего в неё не положили, там будет undefined.

    • Пример: let test; // undefined

  • null: Специальное значение, которое означает «ничего» или «пусто».

    • Пример: let room = null;

  • Symbol: Уникальные идентификаторы для свойств объектов.

2. Объекты (сложные)

  • Object: Используется для хранения коллекций данных и создания сложных сущностей. Массивы и функции в JS — это тоже объекты.

    • Пример: let user = { name: "Ivan", age: 25 };


In JavaScript, there are 8 basic data types. They are divided into two groups: primitives (simple values) and objects (complex structures).

1. Primitive Types

These contain only a single value and are immutable.

  • Number: For any kind of numbers (integer or floating-point).

    • Example: let price = 9.99;

  • BigInt: For integers of arbitrary length that exceed the capacity of the Number type.

    • Example: let giantInt = 12345678901234567890n;

  • String: For textual data.

    • Example: let greeting = "Hello world";

  • Boolean: For logical values.

    • Example: let isRed = false;

  • undefined: A value automatically assigned to variables that have just been declared but not initialized.

    • Example: let x; // undefined

  • null: A separate type that has only one value null, representing "nothing" or "empty".

    • Example: let car = null;

  • Symbol: Used to create unique identifiers for objects.

2. Complex Types

  • Object: Used to store collections of data or more complex entities. Arrays and functions are also objects in JS.

    • Example: let colors = ["red", "green", "blue"];

2
New cards

Разница между == и === (нестрогое/строгое равенство)?

Основная разница между этими операторами заключается в том, приводят ли они типы данных к одному виду перед сравнением или нет.

1. Нестрогое равенство (==)

Этот оператор пытается быть «умным». Если типы данных разные, он автоматически преобразует их, чтобы попытаться найти сходство. Это называется «приведением типов».

  • 5 == "5"true (строка "5" стала числом).

  • true == 1true (true превратилось в 1).

  • null == undefinedtrue (в JS они считаются равными при нестрогом сравнении).

2. Строгое равенство (===)

Этот оператор честный и прямолинейный. Он не меняет типы. Чтобы результат был true, должны совпадать и значение, и тип.

  • 5 === "5"false (число не равно строке).

  • true === 1false (логический тип не равен числу).

  • null === undefinedfalse (разные типы данных).

Совет: В реальной работе почти всегда лучше использовать ===. Это защищает от странных багов, когда "0" внезапно оказывается равен пустой строке.


The main difference between these operators is whether they perform type coercion (type conversion) before comparing.

1. Loose Equality (==)

This operator tries to be "helpful." If the data types are different, it automatically converts them to a common type before comparing.

  • 5 == "5"true (the string "5" is converted to a number).

  • true == 1true (true is converted to 1).

  • null == undefinedtrue (special rule in JS).

2. Strict Equality (===)

This operator is straightforward. It does not convert types. For the result to be true, both the value and the type must be identical.

  • 5 === "5"false (number is not equal to a string).

  • true === 1false (boolean is not equal to a number).

  • null === undefinedfalse (different data types).

Выражение / Expression

Результат ==

Результат ===

0 == ""

true

false

false == 0

true

false

NaN == NaN

false

false (NaN всегда уникален)

Pro Tip: Always prefer ===. It makes your code more predictable and prevents bugs where "0" suddenly equals an empty string.

3
New cards

Что такое Strict mode в JavaScript?

Strict mode («строгий режим») — это специальный режим работы JavaScript, который проверяет код более тщательно и запрещает некоторые «плохие» или устаревшие приемы написания кода.

Как включить

Нужно просто добавить строку "use strict"; в самое начало файла или функции.

Главные особенности:

  1. Запрет неявных глобальных переменных: В обычном режиме, если вы забудете let или const, JS создаст глобальную переменную. В строгом режиме — выдаст ошибку.

    • Пример: "use strict"; x = 10; // Ошибка: x is not defined.

  2. Защита от дублей: Нельзя называть параметры функции одинаковыми именами.

    • Пример: function sum(a, a, b) {} // Ошибка.

  3. Безопасность this: В строгом режиме, если функция вызвана сама по себе (не как метод объекта), this будет равен undefined, а не глобальному объекту window.

  4. Тихие ошибки становятся явными: Операции, которые раньше просто тихо не срабатывали, теперь вызывают ошибку (например, запись в свойство только для чтения).


Strict mode is a way to opt into a restricted variant of JavaScript. It helps you write "cleaner" code and catches common coding mistakes.

How to enable

Add the string "use strict"; at the very top of your script or function.

Key features:

  1. No accidental globals: In normal mode, if you omit let or const, JS creates a global variable. In strict mode, it throws an error.

    • Example: "use strict"; x = 10; // ReferenceError.

  2. No duplicate parameters: You cannot use the same name for multiple function arguments.

    • Example: function sum(a, a, b) {} // SyntaxError.

  3. Safer this: In strict mode, if a function is called without a context, this remains undefined instead of defaulting to the global window object.

  4. Silent errors become loud: It turns silent failures (like writing to a read-only property) into actual errors that stop the script.

4
New cards

Разница между function declaration и function expression?

Главное различие между ними заключается в синтаксисе и всплытии (hoisting) — то есть в том, когда именно вы можете вызвать функцию.

1. Function Declaration (Объявление функции)

Это классический способ. Функция объявляется как отдельная конструкция.

  • Всплытие: Функцию можно вызвать до того, как она описана в коде. JavaScript "видит" её заранее.

  • Синтаксис: Начинается с ключевого слова function.

JavaScript

// Можно вызвать здесь (до объявления)
sayHello(); 

function sayHello() {
  console.log("Привет!");
}

2. Function Expression (Функциональное выражение)

Функция создается внутри выражения (обычно присваивается переменной).

  • Всплытие: Функцию нельзя вызвать до того, как код дойдет до строки с её определением.

  • Синтаксис: Функция находится внутри let, const или var.

JavaScript

// Ошибка! Вызвать до объявления нельзя
// sayHi(); 

const sayHi = function() {
  console.log("Привет!");
};

sayHi(); // Теперь можно

The main difference lies in syntax and hoisting — which determines when you can call the function.

1. Function Declaration

This is a standalone function definition.

  • Hoisting: These functions are hoisted to the top of their scope. You can call them before they appear in the code.

  • Syntax: Starts with the function keyword as a separate statement.

JavaScript

// This works (called before definition)
greet(); 

function greet() {
  console.log("Hello!");
}

2. Function Expression

A function is created and assigned to a variable.

  • Hoisting: These are not hoisted. You must define the function before you can call it.

  • Syntax: Part of a variable assignment.

JavaScript

// Error! Cannot call before definition
// sayBye(); 

const sayBye = function() {
  console.log("Bye!");
};

sayBye(); // Works only here

5
New cards

Разница между null и undefined?

Оба этих значения означают «отсутствие данных», но контекст у них разный.

1. undefined (Не определено)

Это значение «по умолчанию». Оно появляется, когда переменная объявлена, но в неё ничего не положили. Это делает сам JavaScript.

  • Смысл: «Я еще не знаю, что здесь должно быть».

JavaScript

let user; 
console.log(user); // undefined (JS сам поставил это значение)

2. null (Пусто)

Это значение присваивается программистом специально. Оно используется, чтобы явно сказать: «Здесь ничего нет» или «Значение очищено».

  • Смысл: «Я знаю, что здесь пусто, так и задумано».

JavaScript

let user = null; 
console.log(user); // null (Мы сами положили сюда "пустоту")

Важное отличие (typeof)

У них разные типы данных, но есть исторический баг в JS:

  • typeof undefined -> "undefined"

  • typeof null -> "object" (Это официальная ошибка языка, которую не исправляют из-за совместимости).


Both represent "no value," but the intent is different.

1. undefined

This is the default value. It appears when a variable is declared but has not been assigned a value yet. JavaScript assigns this automatically.

  • Meaning: "Value is not assigned yet."

JavaScript

let score;
console.log(score); // undefined (System set this)

2. null

This is assigned intentionally by the developer. It is used to explicitly indicate that a variable is empty or unknown.

  • Meaning: "Intentionally empty."

JavaScript

let score = null;
console.log(score); // null (User set this)

Technical Difference (typeof)

They behave differently with the typeof operator due to a legacy bug:

  • typeof undefined -> "undefined"

  • typeof null -> "object" (A known error in JS, kept for backward compatibility).

6
New cards

Что такое поднятие (Hoisting)?

Hoisting (Поднятие) — это механизм, при котором JavaScript «пробегается» по коду перед его выполнением и поднимает все объявления переменных и функций в самый верх их области видимости.

Простыми словами: вы можете использовать переменные и функции до того, как написали их в коде.

Как это работает на практике

  1. Функции (Function Declaration):

    Поднимаются полностью. Их можно вызывать где угодно.

    JavaScript

    hello(); // Работает! Выведет "Привет"
    
    function hello() {
      console.log("Привет");
    }
    
  2. Переменные var:

    Поднимается только объявление, но не значение. JS знает, что переменная есть, но считает её пустой (undefined).

    JavaScript

    console.log(x); // undefined (ошибки нет, но значения еще нет)
    var x = 5;
    
  3. Переменные let и const:

    Они тоже поднимаются технически, но находятся в «мертвой зоне» (Temporal Dead Zone). Если обратиться к ним до объявления — будет ошибка.

    JavaScript

    console.log(y); // Ошибка: ReferenceError
    let y = 10;
    

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before the code is executed.

In simple terms: you can use variables and functions before you declare them in the code.

How it works in practice

  1. Functions (Function Declaration):

    Hoisted completely. You can call them anywhere.

    JavaScript

    greet(); // Works! Prints "Hello"
    
    function greet() {
      console.log("Hello");
    }
    
  2. Variables (var):

    Only the declaration is hoisted, not the value. JS knows the variable exists but treats it as undefined.

    JavaScript

    console.log(a); // undefined (no error, but no value yet)
    var a = 5;
    
  3. Variables (let and const):

    They are technically hoisted but stay in a "Temporal Dead Zone." Accessing them before declaration causes an error.

    JavaScript

    console.log(b); // Error: ReferenceError
    let b = 10;
    

7
New cards

Что такое область видимости (Scope)?

Область видимости (Scope) — это правила, которые определяют, где именно в коде ваши переменные "видны" и могут быть использованы. Простыми словами: это зона обитания переменной.

В JavaScript есть 3 основных вида:

1. Глобальная (Global Scope)

Переменная объявлена вне любых функций или блоков. Она доступна из любой точки кода.

  • Опасность: Глобальные переменные легко случайно перезаписать.

2. Функциональная (Function Scope)

Переменная объявлена внутри функции. Она доступна только внутри этой функции. Снаружи про неё никто не знает.

  • Особенность: var всегда имеет функциональную область видимости (игнорирует блоки {}).

3. Блочная (Block Scope)

Появилась с let и const. Переменная живет только внутри фигурных скобок { ... }. Это касается условий if, циклов for и просто блоков кода.

JavaScript

let global = "Я везде"; // Глобальная

function myFunc() {
  let funcVar = "Я только в функции"; // Функциональная
  
  if (true) {
    let blockVar = "Я заперт в if"; // Блочная
    var oldVar = "Я var, мне плевать на блок"; // Просочится из блока!
  }
  
  console.log(global); // Работает
  // console.log(blockVar); // Ошибка!
  console.log(oldVar); // Работает (var игнорирует блок)
}

// console.log(funcVar); // Ошибка!

Scope defines where variables are accessible in your code. Put simply: it is the variable's "territory."

There are 3 main types in JavaScript:

1. Global Scope

A variable declared outside any function or block. It can be accessed from anywhere in the code.

  • Risk: Global variables are easy to overwrite accidentally.

2. Function Scope

A variable declared inside a function. It is accessible only within that function. Outside code cannot see it.

  • Note: var always has function scope (it ignores block {}).

3. Block Scope

Introduced with let and const. The variable exists only within curly braces { ... }. This applies to if statements, for loops, and standalone blocks.

JavaScript

let global = "I am everywhere"; // Global

function myFunc() {
  let funcVar = "Inside function only"; // Function scope
  
  if (true) {
    let blockVar = "Trapped in if"; // Block scope
    var oldVar = "I am var, I ignore blocks"; // Leaks out!
  }
  
  console.log(global); // Works
  // console.log(blockVar); // Error!
  console.log(oldVar); // Works (var leaks)
}

// console.log(funcVar); // Error!

8
New cards

Разница между var, let и const?

Это три способа создать переменную, но ведут они себя по-разному. Главные отличия — в области видимости и возможности изменять значение.

1. var (Старый способ)

Сейчас используется редко.

  • Область видимости: Функциональная (виден во всей функции, игнорирует блоки {}).

  • Изменение: Можно менять значение и даже объявлять заново.

  • Странность: Всплывает (hoisting) со значением undefined.

2. let (Современный стандарт)

Используйте, если значение переменной будет меняться.

  • Область видимости: Блочная (живет только внутри {}).

  • Изменение: Можно менять значение, но нельзя объявить заново в том же блоке.

3. const (Константа)

Используйте по умолчанию для всего, что не должно меняться.

  • Область видимости: Блочная (как let).

  • Изменение: Нельзя присвоить новое значение. Но если это объект/массив, его содержимое менять можно.

Сравнение в таблице

Характеристика

var

let

const

Живет внутри

Функции

Блока {}

Блока {}

Можно менять?

Да

Да

Нет

Всплытие

undefined

Ошибка

Ошибка

Пример:

JavaScript

if (true) {
  var a = 1;
  let b = 2;
  const c = 3;
}

console.log(a); // 1 (var вышел из блока)
// console.log(b); // Ошибка (let умер в блоке)
// console.log(c); // Ошибка (const умер в блоке)

These are three ways to declare variables, but they behave differently. The main differences are in scope and reassignment.

1. var (The Old Way)

Rarely used in modern code.

  • Scope: Function-scoped (visible throughout the function, ignores blocks {}).

  • Reassignment: Can be updated and re-declared.

  • Quirk: Hoisted with undefined.

2. let (The Modern Standard)

Use this if the value needs to change later.

  • Scope: Block-scoped (exists only inside {}).

  • Reassignment: Can be updated, but cannot be re-declared in the same block.

3. const (Constant)

Use this by default for anything that shouldn't change.

  • Scope: Block-scoped (like let).

  • Reassignment: Cannot be reassigned. However, if it's an object or array, you can change its contents.

Quick Comparison

Feature

var

let

const

Scoped to

Function

Block {}

Block {}

Can change?

Yes

Yes

No

Hoisting

undefined

Error

Error

Example:

JavaScript

const user = { name: "Alex" };
// user = "John"; // Error! Cannot reassign variable
user.name = "John"; // Works! We changed the content, not the container

9
New cards

Что такое замыкание (Closure)?

Замыкание — это способность функции «запоминать» переменные из того места, где она была создана, и иметь к ним доступ даже после того, как внешняя функция завершила работу.

Простыми словами: это функция плюс все переменные вокруг неё.

Как это работает (Пример с рюкзаком)

Представьте, что функция — это путешественник. Когда она создается внутри другой функции, она собирает «рюкзак» (Closure) и кладет туда все переменные, которые видит вокруг.

Даже если внешняя функция закончила выполнение и исчезла, внутренняя функция уходит гулять со своим «рюкзаком», в котором лежат сохраненные данные.

Пример кода (Счетчик)

Это классический пример. Переменная count спрятана внутри, и к ней нельзя добраться снаружи напрямую, только через возвращенную функцию.

JavaScript

function createCounter() {
  let count = 0; // Эта переменная "замкнётся"

  return function() {
    count++; // Функция помнит count
    console.log(count);
  };
}

const myCounter = createCounter(); // createCounter отработала и умерла

myCounter(); // 1 (но myCounter помнит count!)
myCounter(); // 2
myCounter(); // 3

A Closure is a function that "remembers" the variables from the place where it was created, and can access them even after the outer function has finished executing.

Simply put: it is a function bundled together with its surrounding environment.

How it works (The Backpack Analogy)

Imagine a function is a hiker. When created inside another function, it packs a "backpack" (Closure) containing all the variables it sees around it.

Even if the outer function finishes its job and disappears, the inner function travels on with its "backpack" full of saved data.

Code Example (Counter)

This is the classic example. The count variable is hidden inside; you cannot access it directly from the outside, only through the returned function.

JavaScript

function createCounter() {
  let count = 0; // This variable gets "closed over"

  return function() {
    count++; // The function remembers count
    console.log(count);
  };
}

const myCounter = createCounter(); // createCounter has finished

myCounter(); // 1 (but myCounter still remembers count!)
myCounter(); // 2
myCounter(); // 3

10
New cards

Что обозначает this в JavaScript?

this — это ключевое слово, которое ссылается на объект, который вызывает код в данный момент. Самое главное правило: значение this зависит от того, КАК вызвана функция, а не где она написана.

Проще всего думать об этом как о вопросе: «Кто меня сейчас использует?»

3 главных правила:

  1. Внутри метода объекта (Самое частое)

    Если функция вызывается как часть объекта (через точку), this — это сам объект.

    • Правило: Посмотри налево от точки.

    JavaScript

    const user = {
      name: "Ivan",
      sayHi() {
        console.log(this.name); // this == user
      }
    };
    user.sayHi(); // Выведет "Ivan"
    
  2. В обычной функции (Без объекта)

    Если функцию вызвали просто так, без точки, this ссылается на глобальный объект (в браузере это window).

    • Важно: В строгом режиме ("use strict") this будет undefined.

    JavaScript

    function test() {
      console.log(this);
    }
    test(); // window (или undefined в строгом режиме)
    
  3. В стрелочной функции (=>)

    У стрелочных функций нет своего this. Они берут его у родителя (снаружи), в том месте, где были созданы.

    JavaScript

    const user = {
      name: "Ivan",
      sayHi: () => {
        // Стрелка не видит user, она берет this из глобальной области
        console.log(this.name); 
      }
    };
    user.sayHi(); // undefined (так как this ссылается на window)
    

this is a keyword that refers to the object executing the code at that moment. The most important rule: the value of this depends on HOW the function is called, not where it is written.

Think of it as asking: "Who is calling me right now?"

3 Main Rules:

  1. Inside an Object Method (Most common)

    If a function is called as part of an object (using a dot), this refers to the object itself.

    • Rule of thumb: Look to the left of the dot.

    JavaScript

    const car = {
      brand: "Tesla",
      start() {
        console.log(this.brand); // this == car
      }
    };
    car.start(); // Prints "Tesla"
    
  2. Inside a Standalone Function

    If called simply as a function without an object context, this refers to the Global Object (in browsers, it's window).

    • Note: In Strict Mode, this becomes undefined.

    JavaScript

    function show() {
      console.log(this);
    }
    show(); // window (or undefined in strict mode)
    
  3. Inside an Arrow Function (=>)

    Arrow functions do not have their own this. They inherit it from the surrounding scope (parent context) where they were defined.

    JavaScript

    const group = {
      title: "Developers",
      show: () => {
        // Arrow function doesn't see 'group', it looks at the global scope
        console.log(this.title);
      }
    };
    group.show(); // undefined (because 'this' is window here)