Checkpoint 4 - Variables and data types PART A

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Variables

A variable is a name that is attached to a value

Avoid global variables

Always avoid the following situation in your code: foo = 'bar'; // do other stuff The first line in this snippet is the offending one. We said above that when you define a variable in JavaScript, you should use the let or const keyword. It turns out that you can actually leave out these keywords, and you'll still create a variable. The code snippet above will not trigger an error, but it will create a global variable, and that's to be avoided.

Booleans

Booleans signify truth and falsity. A boolean has two possible values: true and false. In the example, we set loggedIn to true, and we then have a block of code that runs if and only if the user is not logged in. The ! in !loggedIn inverts the Boolean value of the item to the right of it, so !false evaluates to true and !true evaluates to false. let loggedIn = true; if (!loggedIn) { redirectToLoginScreen(); }

Naming variables - Character restrictions

Character restrictions: A variable name must begin with an upper or lower case letter, $, or _. It cannot begin with a number. Numbers can be used elsewhere in the variable name (let myFoo2; is okay). Spaces cannot appear anywhere in the variable name (let my Foo = 'bar';, not okay). Comparison and logical operators cannot be used in variable names (let my+Foo; is not okay).

const Primitive Values

If we assign a primitive value to a constant, we cannot change the primitive value: const PI = 3.141592653589793; PI = 3.14; // This will give an error PI = PI + 10; // This will also give an error

strict mode

JavaScript actually gives us a way to stop code like this from executing: strict mode. Strict mode is a setting you can apply at the top of a JavaScript file: 'use strict'; foo = 'bar'; // => Raises reference error By using strict mode, we can ensure we never create global variables. Unless you have a specific reason not to, it's best to put 'use strict' at the top of all your JavaScript files.

const Assigned when Declared

JavaScript const variables must be assigned a value when they are declared: // Incorrect const PI; PI = 3.14159265359; // Correct const PI = 3.14159265359;

Objects 1/2

Objects are considered to be a complex data type because they combine the primitive data types we've just explored (numbers, strings, Boolean, null, undefined). Objects allow us to have variables that don't point to a single value (say, for instance, a single string) but instead to a collection of values.

Redeclaring Variables with let

Redeclaring a variable using the let keyword can solve this problem. Redeclaring a variable inside a block will not redeclare the variable outside the block: var x = 10; // Here x is 10 { let x = 2; // Here x is 2 } // Here x is 10

Redeclaring Variables with var

Redeclaring a variable using the var keyword can impose problems. Redeclaring a variable inside a block will also redeclare the variable outside the block: var x = 10; // Here x is 10 { var x = 2; // Here x is 2 } // Here x is 2 - See redeclaring a variable with let

Naming variables - reserved words

Reserved words: Reserved words are a special category of words that you're not allowed to use as variable names in a given programming language. For instance, in JavaScript, you can't reassign the name var to a new value (that is, you can't do var = 'some value';). If you try to use a reserved word as a variable name, you'll get an error. Note that reserved words can be used within a variable name (so var varFoo; is legal, even though it's a redundant name).

Strings

Strings are delineated by opening and closing quotes (either single or double, but both must be the same kind — you can't open with a single and close with a double): let foo = 'bar'; and let bar = "foo"; are both valid. Strings are used to represent text. It's basically the case that any character from the Unicode character encoding scheme can be represented in a JavaScript string.

const Not Real Constants

The keyword const is a little misleading. It does NOT define a constant value. It defines a constant reference to a value. Because of this, we cannot change constant primitive values, but we can change the properties of constant objects.

Numbers

The number type in JavaScript is used to represent numbers — both integer values (that is to say, whole numbers like 1, 2, 3, 10000000...) and floating point decimal numbers (that is, numbers like 1.234999).

Data types

A data type is a kind of value that variables can have in a given programming language. JavaScript has six data types: String, Number, Boolean, Null, Undefined, and Object.

Functions

A function is a mini program that you define once in your code and invoke or call elsewhere. function sayHello(personName) { const greeting = "Hi there, " + personName; console.log(greeting); } Functions are values, but not in quite the same way as the preceding data types. Whereas numbers, strings, booleans, null, and undefined all represent a discrete, specific value, a function describes a thing that's a bit hard to pin down: a set of instructions that can be run elsewhere. These instructions can create, manipulate, and reference the simple data types described above. Like any other object, a function can be passed around your code and assigned to a variable. You can write a set of instructions once and invoke or call that set of instructions elsewhere in your code.

Choose meaningful variable names

Choose meaningful variable names: When we learned about HTML, we learned about the idea of semantic HTML, which says that the type of element we choose should reflect the type of content that element provides. In a similar way, when we choose variable names in JavaScript, we should choose names that reflect how the variable gets used in the program. A well-chosen variable name can help other people reading the code to understand how the variable is intended to be used. In the click counter app at the top of this reading, we had the variable name clickCount. When you read that name, you already have a sense of what it does. If we had named that same variable y, the code would have worked exactly the same, but its meaning would be less clear.

Defining variables with var

Creating variables with var is almost identical to creating them with let. var pi = 3.14159; console.log(pi); // => 3.14159 pi = 3.1; console.log(pi); // 3.1 The syntax above is identical to what we saw with let, except for the use of var. As with let, we can initially declare variables with var, without assigning a value. var myVar; myVar = 6;

const Block Scope

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 = 10; // Here x is 10 { const x = 2; // Here x is 2 } // Here x is 10

Loop Scope - Using let in a loop

Using let, the variable declared in the loop does not redeclare the variable outside the loop: let i = 5; for (let i = 0; i < 10; i++) { // some statements } // Here i is 5

Loop Scope - Using var in a loop

Using var, the variable declared in the loop redeclares the variable outside the loop: var i = 5; for (var i = 0; i < 10; i++) { // some statements } // Here i is 10

Global Scope

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program: var carName = "Volvo"; // code here can use carName function myFunction() { // code here can also use carName }

Function Scope

Variables declared Locally (inside a function) have Function Scope. Local variables can only be accessed from inside the function where they are declared: // code here can NOT use carName function myFunction() { var carName = "Volvo"; // code here CAN use carName } // code here can NOT use carName

JavaScript Block Scope

Variables declared with the var keyword can not have Block Scope. Variables declared inside a block {} can be accessed from outside the block.Before ES2015 JavaScript did not have Block Scope. Variables declared with the let keyword can have Block Scope: { var x = 2; } // x CAN be used here Variables declared inside a block {} can not be accessed from outside the block: { let x = 2; } // x can NOT be used here

const

Variables defined with const behave like let variables, except they cannot be reassigned: const PI = 3.141592653589793; PI = 3.14; // This will give an error PI = PI + 10; // This will also give an error

Hoisting

Variables defined with var are hoisted to the top. Variables defined with let are not hoisted to the top. // you CAN use carName here var carName; // you can NOT use carName here let carName;

undefined

We encountered undefined in the previous assignment when we discussed declaring variables before assigning values to them. undefined is a special value that the browser assigns to variables when it first creates them in memory. You should never directly set a value to undefined. It's fine to check if a variable is undefined, but you shouldn't do: let foo = undefined;. If you want to represent the absence of a value, use null.

const Constant Objects can Change

You can change the properties of a constant object: // 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 a constant object: const car = {type:"Fiat", model:"500", color:"white"}; car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR

camelCasing

camelCasing: JavaScript developers have an unwritten agreement to use camel-casing for variable names. Camel-casing looks like this: thisIsCamelCasing. A camel-cased variable name starts with a lowercase letter, and then uses lowercase letters throughout, except for the first letter of any new words in the variable name after the first — for these first letters, use uppercase. There are agreed upon cases where we use TitleCasing in JavaScript (for instance, when creating object constructors, which is an advanced topic that you don't need to understand at the moment), but the general rule is use camel-casing.

Defining constants with const

const is used to define constant values, which is another way of saying variables whose value cannot be reassigned: const pi = 3.14159; console.log(pi); // => 3.14159

Defining variables with let

let is used to define variables whose values can (but need not) be reassigned: let pi = 3.14159; console.log(pi); // => 3.14159 pi = 3.1; console.log(pi); // 3.1

null

null is a special value used to indicate that a variable has no value. It's not uncommon to see code that defaults to assigning null when other data is not available. Be aware that if you run typeof null in JavaScript, you'll get an eyebrow-raising answer: "object". Even though null is a distinct data type, typeof says it's an object. This is a relic of a much earlier version of JavaScript that was not fixed in ES5 or ES6.


Ensembles d'études connexes

AZ-900 Practice Test 4 - Q1-55 - NEW

View Set

DECA Marketing Cluster Questions

View Set

PSY 252: Social Psychology Final Exam

View Set