[monderJS] let, const, and var

김민지·2022년 11월 6일

Learned


  1. Variables
  2. let,var,and const

Variables

  • A variable is a "names storage" for data. We can use variables to store goodies, visitors, and other data
  • We can declare multiple variables in many different ways but have to consider eradability.
let user = 'MJ',
let age = '99',
let message = 'wanna go home';

Let

  • When the value is changed, the old data is removed from the variable
let message;

message = 'I study better at night';

// old data is removed and the value changed
message = 'I'll study in the morning when I'm fresh'

alert(message);
  • We can also declare two variables and copy data from one into the other
let hello = 'Hello MJ';

let message;

message = hello; // copy 'Hello MJ' from hello into message

// Now two variables hold the same data
alert(hello) // Hello MJ
alert(message) // Hello MJ

Var

  • In order scripts, you may also find another keyword "var" instead of let
var message = 'Hello'; 
  • The var keyword is almost the same as let.
    - It also declares a variable, but in a slightly different way
    • we'll get back to this topic later

Constants

  • To declare a constant (unchanging) variable, use const instead of let:
  • There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution
  • Such constants are named using capital letters and underscores
const COLOR_RED = "#FOO";

Summary

  • We can declare variables to store data by using the var, let, or const keywords.
  • var variables can be updated and re-declated within its scope
  • let variables can be updated but not re-declared.
  • const variables can neither be updated nor re-declared.

Tasks


  • Working with variables
  1. Declare two variables: admin and name.
  2. Assign the value "John" to name.
  3. Copy the value from name to admin
  4. Show the value of admin using alert (must output "John")
// How I did
let admin;
let name = "John";
admin = name;

alert(admin)
// Soln
let admin, name; // ahh I could've declared two variables at once!!
name = "John";
admin = name;

alert(admin)
  • Uppercase const
    - Would it be right to use upper case for birthday? for age? Or even both?
const birthday = '18.04.1982';

const age = someCode(birthday);
  • The value of birthday is hard-coded whereas variable "age" is evaluated in run-time. Therefore, it would be proper to use uppercase to birthday only.
profile
노는게 제일 좋아

0개의 댓글