Стрілкові функції в JavaScript

Стрілкові функції в JavaScript – це не просто скорочений синтаксис, а справжні магічні стріли, які можуть зробити ваш код більш читабельним та зручним. Ось декілька цікавих речей, які ви можете робити з ними:

Короткі функції з одним виразом: Стрілкові функції ідеально підходять для коротких функцій, які повертають один результат. Наприклад:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    const numbers = [1, 2, 3, 4, 5];
    const squared = numbers.map((num) => num ** 2);
    console.log(squared); // Виведе [1, 4, 9, 16, 25]
    const numbers = [1, 2, 3, 4, 5]; const squared = numbers.map((num) => num ** 2); console.log(squared); // Виведе [1, 4, 9, 16, 25]
    const numbers = [1, 2, 3, 4, 5];
    const squared = numbers.map((num) => num ** 2);
    console.log(squared); // Виведе [1, 4, 9, 16, 25]

    Callback-функції: Вони дуже зручні для використання в методах масивів, таких як mapfilterreduce:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    const numbers = [1, 2, 3, 4, 5];
    const squared = numbers.map((num) => num ** 2);
    console.log(squared); // Виведе [1, 4, 9, 16, 25]
    const numbers = [1, 2, 3, 4, 5]; const squared = numbers.map((num) => num ** 2); console.log(squared); // Виведе [1, 4, 9, 16, 25]
    const numbers = [1, 2, 3, 4, 5];
    const squared = numbers.map((num) => num ** 2);
    console.log(squared); // Виведе [1, 4, 9, 16, 25]
    

    Лексичне прив’язування this: Стрілкові функції автоматично прив’язують this до контексту, в якому вони були створені. Це уникне багатьох проблем, зокрема при роботі з об’єктами та подіями.

    Ланцюги обіцянок (Promises): Стрілкові функції можна використовувати в асинхронних операціях:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    const fetchData = async () => {
    try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
    } catch (error) {
    console.error('Something went wrong:', error);
    }
    };
    const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Something went wrong:', error); } };
    const fetchData = async () => {
        try {
            const response = await fetch('https://api.example.com/data');
            const data = await response.json();
            console.log(data);
        } catch (error) {
            console.error('Something went wrong:', error);
        }
    };
    

    Параметри за замовчуванням та розпакування: Ви можете використовувати параметри за замовчуванням та розпаковування:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    const greet = (name = 'Friend') => `Hello, ${name}!`;
    console.log(greet()); // Виведе "Hello, Friend!"
    const greet = (name = 'Friend') => `Hello, ${name}!`; console.log(greet()); // Виведе "Hello, Friend!"
    const greet = (name = 'Friend') => `Hello, ${name}!`;
    console.log(greet()); // Виведе "Hello, Friend!"
    

    Отже, стрілкові функції – це не просто стріли, вони – ваші надійні помічники у світі JavaScript! 🚀1 2 3 4 5.

    Javascript: Closures, callback, context

    A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    window.onload = function(){
    var item = document.querySelector(".items .item");
    item onClick = activeItem;
    function activeItem() {
    console.log(item);
    }
    }
    window.onload = function(){ var item = document.querySelector(".items .item"); item onClick = activeItem; function activeItem() { console.log(item); } }
    window.onload = function(){
        var item = document.querySelector(".items .item");
        item onClick = activeItem;
    
        function activeItem() {
            console.log(item);
        }
    }

    In this example inner function activeItem() have access to global variable item. This called closure – when inner function have access to all variables, defined in global function.

    JavaScript: Type conversion

    To show variable type use typeof:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    let value = true;
    console.log(typeof value); // boolean
    let value = true; console.log(typeof value); // boolean
    let value = true;
    console.log(typeof value); // boolean

    Let’s convert our variable to string:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    value = String(value); // now value is a string "true"
    console.log(typeof value); // string
    value = String(value); // now value is a string "true" console.log(typeof value); // string
    value = String(value); // now value is a string "true"
    console.log(typeof value); // string

    Numeric Conversion

    Numeric conversion happens in mathematical functions and expressions automatically.

    For example, when division / is applied to non-numbers:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    console.log( "6" / "2" ); // 3, strings are converted to numbers
    console.log( "6" / "2" ); // 3, strings are converted to numbers
    console.log( "6" / "2" ); // 3, strings are converted to numbers

    We can use the Number(value) function to explicitly convert a value to a number:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    let str = "123";
    console.log(typeof str); // string
    let num = Number(str); // becomes a number 123
    console.log(typeof num); // number
    let str = "123"; console.log(typeof str); // string let num = Number(str); // becomes a number 123 console.log(typeof num); // number
    let str = "123";
    console.log(typeof str); // string
    
    let num = Number(str); // becomes a number 123
    console.log(typeof num); // number

    Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.

    If the string is not a valid number, the result of such a conversion is NaN. For instance:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    let age = Number("an arbitrary string instead of a number");
    console.log(age); // NaN, conversion failed
    let age = Number("an arbitrary string instead of a number"); console.log(age); // NaN, conversion failed
    let age = Number("an arbitrary string instead of a number");
    console.log(age); // NaN, conversion failed

    Examples of numeric conversion:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    console.log( Number(" 123 ") ); // 123
    console.log( Number("123z") ); // NaN (error reading a number at "z")
    console.log( Number(true) ); // 1
    console.log( Number(false) ); // 0
    console.log( Number(" 123 ") ); // 123 console.log( Number("123z") ); // NaN (error reading a number at "z") console.log( Number(true) ); // 1 console.log( Number(false) ); // 0
    console.log( Number(" 123 ") ); // 123
    console.log( Number("123z") );  // NaN (error reading a number at "z")
    console.log( Number(true) );    // 1
    console.log( Number(false) );   // 0

    Please note that null and undefined behave differently here: null becomes zero while undefined becomes NaN.

    Boolean Conversion

    The conversion rule:

    Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.
    Other values become true.

    For instance:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    console.log( Boolean(1) ); // true
    console.log( Boolean(0) ); // false
    console.log( Boolean("hello") ); // true
    console.log( Boolean("") ); // false
    console.log( Boolean(1) ); // true console.log( Boolean(0) ); // false console.log( Boolean("hello") ); // true console.log( Boolean("") ); // false
    console.log( Boolean(1) ); // true
    console.log( Boolean(0) ); // false
    
    console.log( Boolean("hello") ); // true
    console.log( Boolean("") ); // false

    Summary

    The three most widely used type conversions are to string, to number, and to boolean.

    String Conversion – Occurs when we output something. Can be performed with String(value). The conversion to string is usually obvious for primitive values.

    Numeric Conversion– Occurs in math operations. Can be performed with Number(value).

    Boolean Conversion – Occurs in logical operations. Can be performed with Boolean(value).

    Best JavaScript libraries

    Lodash (https://lodash.com/)

    Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodash’s modular methods are great for:

    • Iterating arrays, objects, & strings
    • Manipulating & testing values
    • Creating composite functions

    Quill Text Editor (https://quilljs.com/)

    Quill is a free, open source WYSIWYG editor built for the modern web. With its modular architecture and expressive API, it is completely customizable to fit any need.


    Leaflet (https://leafletjs.com/)

    Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 39 KB of JS, it has all the mapping features most developers ever need.

    Leaflet is designed with simplicity, performance and usability in mind. It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use and well-documented API and a simple, readable source code that is a joy to contribute to.