The var
declares a variable with function scope.
Scope essentially means where these variables are available for use. var
declarations are globally scoped or function/locally scoped.
The scope is global when a var
variable is declared outside a function. This means that any variable that is declared with var
outside a function block is available for use in the whole window.
var
is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.
To understand further, look at the example below.
var greeter = "hey hi";
function newFunction() {
var hello = "hello";
}
Here, greeter
is globally scoped because it exists outside a function while hello
is function scoped. So we cannot access the variable hello
outside of a function. So if we do this:
var tester = "hey hi";
function newFunction() {
var hello = "hello";
}
console.log(hello); // error: hello is not defined
We'll get an error which is as a result of hello
not being available outside the function.
This means that we can do this within the same scope and won't get an error.
var greeter = "hey hi";
var greeter = "say Hello instead";
and this also
var greeter = "hey hi";
greeter = "say Hello instead";
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:
console.log (greeter);
var greeter = "say hello"
it is interpreted as this:
var greeter;
console.log(greeter); // greeter is undefined
greeter = "say hello"
So var
variables are hoisted to the top of their scope and initialized with a value of undefined
.
There's a weakness that comes with var
. I'll use the example below to explain:
var greeter = "hey hi";
var times = 4;
if (times > 3) {
var greeter = "say Hello instead";
}
console.log(greeter) // "say Hello instead"
So, since times > 3
returns true, greeter
is redefined to "say Hello instead"
. While this is not a problem if you knowingly want greeter
to be redefined, it becomes a problem when you do not realize that a variable greeter
has already been defined before.
If you have used greeter
in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why let and const are necessary.
A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.
So a variable declared in a block with let
is only available for use within that block. Let me explain this with an example:
let greeting = "say Hi";
let times = 4;
if (times > 3) {
let hello = "say Hello instead";
console.log(hello);// "say Hello instead"
}
console.log(hello) // hello is not defined
We see that using hello
outside its block (the curly braces where it was defined) returns an error. This is because let
variables are block scoped.
Just like var, a variable declared with let
can be updated within its scope. Unlike var
, a let
variable cannot be re-declared within its scope. So while this will work:
let greeting = "say Hi";
greeting = "say Hello instead";
this will return an error:
let greeting = "say Hi";
let greeting = "say Hello instead"; // error: Identifier 'greeting' has already been declared
However, if the same variable is defined in different scopes, there will be no error:
let greeting = "say Hi";
if (true) {
let greeting = "say Hello instead";
console.log(greeting); // "say Hello instead"
}
console.log(greeting); // "say Hi"
Why is there no error? This is because both instances are treated as different variables since they have different scopes.
This fact makes let
a better choice than var
. When using let
, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.
Also, since a variable cannot be declared more than once within a scope, then the problem discussed earlier that occurs with var
does not happen.
Just like var, let
declarations are hoisted to the top. Unlike var
which is initialized as undefined
, the let
keyword is not initialized. So if you try to use a let
variable before the declaration, you'll get a Reference Error
.
Like let declarations, const
declarations can only be accessed within the block they were declared.
This means that the value of a variable declared with const
remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const
, we can neither do this:
const greeting = "say Hi";
greeting = "say Hello instead";// error: Assignment to constant variable.
nor this:
const greeting = "say Hi";
const greeting = "say Hello instead";// error: Identifier 'greeting' has already been declared
Every const
declaration, therefore, must be initialized at the time of declaration.
This behavior is somehow different when it comes to objects declared with const
. While a const
object cannot be updated, the properties of this objects can be updated. Therefore, if we declare a const
object as this:
const greeting = {
message: "say Hi",
times: 4
}
while we cannot do this:
greeting = {
words: "Hello",
number: "five"
} // error: Assignment to constant variable.
we can do this:
greeting.message = "say Hello instead";
This will update the value of greeting.message
without returning errors.
Just like let, const
declarations are hoisted to the top but are not initialized.
So just in case you missed the differences, here they are:
var
declarations are globally scoped or function scoped while let
and const
are block-scoped.var
variables can be updated and re-declared within its scope; let
variables can be updated but not re-declared; const
variables can neither be updated nor re-declared.var
variables are initialized with undefined
, let
and const
variables are not initialized.var
and let
can be declared without being initialized, const
must be initialized during declaration.The let keyword was introduced in ES6 (2015).
The const keyword was introduced in ES6 (2015).
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let
and const
.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block.
{ let x = 2; } // x can NOT be used here
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with var
, let
and const
are quite similar when declared inside a function.
function varFunction() {
var message = "Hello"; // Function Scope
}
function letFunction() {
let message = "Hello"; // Function Scope
}
function constFunction() {
const message = "Hello"; // Function Scope
}
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
Variables declared with var
, let
and const
are quite similar when declared outside a block.
var x = 2; // Global scope let x = 2; // Global scope const x = 2; // Global scope
The var statement declares a variable.
Variables are containers for storing information.
Creating a variable in JavaScript is called "declaring" a variable:
var message;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
message = "Hello";
You can also assign a value to the variable when you declare it:
var message = "Hello";
The const
keyword was introduced in ES6 (2015).
const
cannot be Redeclared.const
cannot be Reassigned.const
have Block Scope.When to use JavaScript const? As a general rule, always declare a variable with const unless you know that the value will change.
The let
keyword was introduced in ES6 (2015).
let
cannot be Redeclared.let
must be Declared before use.let
have Block Scope.Chosen is an extensive plugin that not only restyles your select elements but provides additional functionality such as in-select searching, multiple element selection, and highlighting.
JavaScript's forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, using the break statement is a syntax error:
[1, 2, 3, 4, 5].forEach(v => {
if (v > 3) {
// SyntaxError: Illegal break statement
break;
}
});
We recommend using for/of loops to iterate through an array unless you have a good reason not to. However, if you find yourself stuck with a forEach() that needs to stop after a certain point and refactoring to use for/of is not an option, here are four workarounds.
The every() function behaves exactly like forEach(), except it stops iterating through the array whenever the callback function returns a false value.
// Prints "1, 2, 3" [1, 2, 3, 4, 5].every(v => { if (v > 3) { return false; } console.log(v); // Make sure you return true. If you don't return a value, `every()` will stop. return true; });
With every(), return false is equivalent to a break, and return true is equivalent to a continue.
Another alternative is to use the find() function, which is similar but just flips the boolean values. With find(), return true is equivalent to break, and return false is equivalent to continue.
Instead of thinking about how to break out of a forEach(), try thinking about how to filter out all the values you don't want forEach() to iterate over. This approach is more in line with functional programming principles.
The findIndex() function takes a callback and returns the first index of the array whose value the callback returns truthy for. Then the slice() function copies part of the array.
// Prints "1, 2, 3" const arr = [1, 2, 3, 4, 5]; // Instead of trying to `break`, slice out the part of the array that `break` // would ignore. arr.slice(0, arr.findIndex(v => v > 3)).forEach(v => { console.log(v); });
If you can't use every() or slice(), you can check a shouldSkip flag at the start of your forEach() callback. If you set shouldSkip to true, the forEach() callback returns immediately.
// Prints "1, 2, 3" let shouldSkip = false; [1, 2, 3, 4, 5].forEach(v => { if (shouldSkip) { return; } if (v > 3) { shouldSkip = true; return; } console.log(v); });
This approach is clunky and inelegant, but it works with minimum mental overhead. You can use this approach if the previous approaches seem too clever.
The forEach() function respects changes to the array's length property. So you can force forEach() to break out of the loop early by overwriting the array's length property as shown below.
const myNums = [1, 2, 3, 4, 5]; myNums.forEach((v, index, arr) => { console.log(v); if (val > 3) { arr.length = index + 1; // Behaves like `break` } }
While this approach works, it also mutates the array! If you change the array's length, you effectively truncate the array: subsequent operations, like for/of or JSON.stringify() will only go through the shortened version of the array. Using this approach to break out of a forEach() loop is not recommended.
Arrays are ordered collections of values, and they are perhaps the most commonly used data structure in JavaScript. Elements in an array can be accessed by their index, and arrays can hold values of different data types.
let myArray = [1, 2, 3, 4, 5];
console.log(myArray[0]); // Accessing the first element
Objects in JavaScript are collections of key-value pairs. They are versatile and can be used to represent a wide range of data structures. Objects are often used for creating dictionaries, maps, and records.
let person = {
name: "Maria",
age: 28,
city: "New York"
};
console.log(person.name); // Accessing a property
Keys are always strings (or Symbols, introduced in ES6). When you use non-string values as keys in an object, JavaScript implicitly converts them to strings.
Objects are generally used for a simple dictionary-like structure with string keys.
Some JavaScript content delivery networks (CDN):
In this Ionic 5/4 tutorial, we’ll discuss how to add a Sortable list with Drag and Drop feature using the Ion Reorder UI component in Ionic Angular application.
Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
Getting Started | Select2 - The jQuery replacement for select boxes
To add multiple window.onload
events you can use
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', myFunction, false); // not 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', myFunction);
}
A lightweight, simple, beautiful JSON viewer and editor plugin helps the developers to render JSON objects in HTML with collapsible/expandable navigation just like a tree view.
Yet another jQuery JSON viewer plugin that renders JSON objects in HTML with support for syntax highlighting and collapsible/expandable navigation.
Yet another JSON viewer library that renders your JSON data as a collapsible and expandable tree structure for better readability.
A super lightweight, pure JavaScript JSON formatter / viewer which helps render JSON objects just like a collapsible tree view.
The Vanilla JavaScript version of the jQuery JSON Path Picker, which helps you render your JSON data in a collapsible tree structure where you can get the path to each key by clicking on the output icon.
Expando is a tiny jQuery-powered JS Object Viewer/Editor that helps developers creates a very nice expandable tree hierarchy of your data.
With this plugin you can create an editable tree with collapsible branches to easily browse/edit JavaScript objects and their properties.
Tree-style Expanding JS Object Viewer/Editor In jQuery - Expando
The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
Spread operator doing concat
let arrayOne = [1, 2, 3];
let arraryTwo = [4, 5];
arrayCombined = [...arrayOne,...arrayTwo];
Add item using spread operator
let arrayOne = [1, 2, 3];
arrayNew = [...arrayOne, 3];
JavaScript scope refers to the context in which variables, functions, and objects are defined. It determines the accessibility and visibility of these elements within the code. Understanding scope is crucial for writing maintainable and error-free JavaScript code.
JavaScript has three types of scope:
JavaScript collections refer to data structures in the JavaScript programming language that are used to store and manipulate collections of values or objects. These collections provide various ways to organize and access data efficiently. There are several built-in collection types in JavaScript, and developers can also create custom collections as needed.
In JavaScript, collections like arrays, objects, sets, and maps are built-in language features. They are part of the core JavaScript language and do not require any external extensions or libraries to use. JavaScript provides these data structures as fundamental constructs for working with and organizing data within your programs.
JavaScript's forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, using the break statement is a syntax error.
Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.
Variables are containers for storing data in JavaScript. JavaScript variables can be declared in 4 ways:
var
: Declares a variable with function scope. It's less commonly used in modern JavaScript due to its potential for scope-related issues.
let
: Declares a variable with block scope, limiting it to the block or statement in which it's defined. It allows reassignment.
const
: Declares a constant variable with block scope. Once assigned, its value cannot be changed.
Choosing between them depends on your needs for variable scope and mutability. const
is preferred when you don't intend to change the variable's value, while let
is suitable for variables that need to be reassigned. var
is generally avoided in modern JavaScript due to its quirks related to scope.
We'll discuss the differences in Scope, Redeclaration, and Hoisting.
let is now preferred for variable declaration. It's no surprise as it comes as an improvement to var declarations. It also solves the problem with var that we just covered. Let's consider why this is so.
Before the advent of ES6, var declarations ruled. There are issues associated with variables declared with var, though. That is why new ways needed to declare variables to emerge.
JavaScript is a versatile and widely-used programming language, known for its ability to add interactivity and dynamic behavior to web pages. Key features include its simplicity, support for both front-end and back-end development, asynchronous capabilities, and a vast ecosystem of libraries and frameworks, making it essential for modern web development.
Axios is a popular JavaScript library that simplifies HTTP requests, making it easy for beginners to interact with web services and APIs. With a simple and intuitive syntax, Axios provides a clean way to handle asynchronous tasks in web development. Whether fetching data or sending requests, Axios streamlines the process, enhancing the efficiency of frontend development.
Make Axios send cookies in its requests automatically.
You can use the withCredentials
property.
axios.get(BASE_URL + '/todos', { withCredentials: true });
Also it is possible to force credentials to every Axios requests
axios.defaults.withCredentials = true
Or using credentials for some of the Axios requests as the following code
const instance = axios.create({
withCredentials: true,
baseURL: BASE_URL
})
instance.get('/todos')
In JavaScript, an array is a special object that provides a way to store and organize data. It is a linear, ordered collection of elements, and an index can access each element. The array object in JavaScript comes with various built-in methods for manipulating and working with arrays.
The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise, it returns false. It doesn't modify the array.
Reference: Array.prototype.some() - JavaScript | MDN (mozilla.org)
JavaScript functions are reusable blocks of code that perform specific tasks. Defined using the function keyword or as arrow functions, they can accept parameters and return values. Functions enhance code organization, modularity, and reusability, allowing developers to execute the same logic multiple times throughout a program with ease.
TinyMCE Fiddle is an online platform that allows developers to experiment with and test TinyMCE editor configurations in real-time. It provides a user-friendly interface to modify settings, integrate plugins, and preview changes instantly, facilitating efficient development and customization of the TinyMCE rich-text editor.
Go to TinyMCE Fiddle