Variables, Built-in Functions

Some Definitions

We learned how to produce values from using operators on other values. We created expressions!.

  • expression - a fragment of code that produces a value
    • not a statement by itself
    • every literal value is an expression - 27, "YES!"
  • statement - a full instruction/action for the computer
    • in JavaScript most statements end in a semicolon (;)
    • the simplest statement is an expression with a semicolon at the end - 27;, "YES!";
  • program - a sequence of statements that specify to a computer actions to perform
  • function - a named sequence of code that can be called by name
  • built-in function - a function available in the global namespace that is part of the core language

A Quick Note on Functions

If you declare a function using this (function declaration) syntax:

// function declaration, a single statement

function f() {

    // do stuff

}

… you have a single statement (note, no semicolon at the end).

However, any statement that:

  • involves functions
  • but doesn't start with the actual keyword, function
  • will have a function expression (that is, an expression that evaluates to a function) in it:

 

const foo = function bar(bax) {}; // <-- function expression

const qux = function(corge) {}; // <-- function expression

 

Soooo… most statements end with a semicolon.

 

Variables

Variables are symbolic names for values; you can use a variable's name wherever you want to use that value.

To create a variable, start with one of the following keywords:

  • const or let (ES6) … or var
  • followed by a variable name
  • optionally, assign a value to the variable by using = and a value or expression
  • of course, you can add a semicolon (or not)
  • notice that type does not have to be specified!

 

const s = 'hello';

let i = 21 * 2;

console.log(s);

console.log(++i);

 

Block Scope w/ const or let (ES6)

Wait, so it looks like there are three ways to declare variables. What's the difference? Let's look at const and let first

  • the scope of variables declared with const and let is the block that they're contained in
  • a block is simply the area between opening and closing curly braces

 

{

   const s = 'in'; // just need two curly braces to make a block!

}

for(let i = 0; i < 10; i++) {

   const s = 'also in'; // for loop body is a block!

}

function f() {

   const s = 'in too'; // function body is a block!

}

 

Block Scope Continued

Accessing a variable when it's out of scope produces a run-time error (specifically a ReferenceError)!

console.log('out there');

{

   const s = 'in here'; 

}

console.log(s);

(heeeey… sort of just like Java)

Variables in an outer scope are visible from an inner scope:

{

    const first = 'out there';

    {

        const full = `${first} in here`;

        console.log(full);

    }

}

 

 

const vs let

OK… so what's the difference between const and let then?

  • a variable declared with const can't be assigned a different value after it had been declared
  • const reassignment will result in a run-time error (TypeError)const dontChangeMe = "I told you so";
  • dontChangeMe = "why not?";
  • note, however, that this  does not mean the variable is immutable
  • in fact, if a const declared variable is mutable, it can still be changed without errorconst arr = [1, 2, 3];
  • arr[0] = 'wat? this is ok!?';
  • console.log(arr);
  • on the other hand, let declared variables can be reassignedlet i = 0;
  • i = i + 2;
  • console.log(i);

 

const vs let Continued

Again, a value cannot be assigned to a const declared variable after it's been declared. This implies that…

  • from mdn: "An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared"
  • or, simply put, you must assign a value immediately when declaring a variable with const
  • otherwise, you'll get a syntax error:const foo;
  • foo = 'bar'
  • // SyntaxError: Missing initializer in const declaration

 

Default Initial Value

When you declare a variable without assigning a value to it, it will be initialized to undefined (this is really only valid for let and var, of course). →

For example, the output of this…

let a;

console.log(a);

is

undefined

 

Redeclaring Variables with let and const

If a variable has already been declared (with let, const, or var)… →

  • redeclaring a variable with the same identifier (name) with let and const will result in a SyntaxError
  • for example:let i = 0;
  • let i = 1;

 

A Note About Loops

let and const behavior in loops: →

  • if the loop variable is incremented/decremented, it must be declared as 'let':for(let i = 0; i < 10; i++) { console.log(i); }    
  • repeatedly creating a variable with let or const in a loop body does not count as redeclaration (works fine; it's another scope!)for(let i = 0; i < 10; i++) { 
  •   const j = i * 2;
  •   console.log(j);
  • }    

 

Always use const or let (or var, I guess) when declaring variable names!

If you don't declare variables with these keywords:

  • you get global variables!
  • This is particularly important when dealing with variable declarations in functions

And Speaking of a Look of Disapproval

(Variable Names)

What are the rules for a valid identifier (variable name) again?

  • start with a letter, underscore ( _ ), or dollar ( $ )
  • following characters can be any of above, and/or digits (0-9)
  • can't use reserved words / keywords

 

Don't Do This, But…

BTW, Unicode characters are allowed in variable names!!!

const ಠ_ಠ = "disapproval";

console.log(ಠ_ಠ);

// totally works (O_o !?)

Thanks Stackoverflow! Also, here's more about that look.

Oh, and this is a site that let's you check if a variable name is valid or not.

 

Another Note on Variables

Because JavaScript is dynamically typed… variable reassignment (for let and var, even of different types, is ok

let x = 25;

x = "foo";

Lastly, a quick aside…

posted @ 2023-01-25 10:27  M1stF0rest  阅读(22)  评论(0编辑  收藏  举报