const PI = 3.141592653589793; PI = 3.14; // This will give an error PI = PI + 10; // This will also give an error // JavaScript const variables must be assigned a value when // they are declared : // Correct const PI = 3.14159265359; // Incorrect const PI; PI = 3.14159265359; // Always declare a variable with const when you know that // the value should not be changed. // Use const when you declare: // * A new Array // * A new Object // * A new Function // * A new RegExp //You can change the elements of a constant array : // You can create a constant array : const cars = ["Saab", "Volvo", "BMW"]; // You can change an element : cars[0] = "Toyota"; // You can add an element : cars.push("Audi"); // But you can NOT reassign the array : const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; // This creates an ERROR // You can create a const object : const car = {type:"Fiat", model:"500", color:"white"}; // You can change a property: car.color = "red"; // You can add a property: car.owner = "Johnson"; // But you can NOT reassign the object : const car = {type:"Fiat", model:"500", color:"white"}; car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR // Declaring a variable with const is similar to let when it // comes to Block Scope. The x declared in the block, in this // example, is not the same as the x declared outside the // block: const x = 10; // Here x is 10 { const x = 2; // Here x is 2 } // Here x is 10 // Declaring a variable with const is similar to let when it // comes to Block Scope. The x declared in the block, in this // example, is not the same as the x declared outside the // block: var x = 2; // Allowed var x = 3; // Allowed x = 4; // Allowed // New Example var x = 2; // Allowed const x = 2; // Not allowed { let x = 2; // Allowed const x = 2; // Not allowed } { const x = 2; // Allowed const x = 2; // Not allowed //New Example const x = 2; // Allowed x = 2; // Not allowed var x = 2; // Not allowed let x = 2; // Not allowed const x = 2; // Not allowed { const x = 2; // Allowed x = 2; // Not allowed var x = 2; // Not allowed let x = 2; // Not allowed const x = 2; // Not allowed //New Example const x = 2; // Allowed { const x = 3; // Allowed } { const x = 4; // Allowed }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter