Files
.github
api-server
client
config
curriculum
docs
guide
arabic
chinese
english
3d
accessibility
agile
algorithms
android-development
angular
angularjs
apache
aspnet
bash
blender
blockchain
book-recommendations
bootstrap
bsd-os
bulma
c
canvas
certifications
chef
clojure
cloud-development
computational-genomics
computer-hardware
computer-science
containers
cplusplus
csharp
css
d3
data-science-tools
design-patterns
designer-tools
developer-ethics
developer-tools
devops
docker
documentation
drupal
electron
elixir
elm
erlang
fsharp
game-development
gatsbyjs
git
go
groovy
haskell
hibernate
html
ionic
java
javascript
additional-javascript-resources
advantages-and-disadvantages-of-javascript
angularjs-interview-questions
arguments
arithmetic-operation
arrow-functions
assignment-operators
async-messaging-with-rabbitmq-tortoise
await-promises
booleans
callback-functions
classes
closures
code-blocks
code-linting-in-javascript
comments
comparison-operators
concurrency-model-and-event-loop
conditional-ternary-operators
converting-strings-to-numbers
error-handling-and-try-catch-throw
es6
falsy-values
form-validation
function-composition
function-invocation
functions-list
get-timestamp
global-object
global-variables
higher-order-functions
html-dom
html-dom-getelementbyid-method
html-dom-innerhtml-property
html-dom-queryselector
if-else-statement
immediately-invoked-functions-expressions
immutable-types
location-object
location-reload-method
logical-operators
loops
manipulate-javascript-objects
manipulating-cookies
multiply-two-numbers-with-javascript
naming-convention-for-javascript
numbers
object-instantiation
onclick-event
onload-event
output
popup-boxes
promises
prototypes
random-method
regular-expressions-reference
rest-parameters
return-statements
scopes
semicolons
singleton-in-javascript
spread-syntax
standard-objects
strict-mode
switch-statements
template-literals
ternary-operator
this-reference
timing-events
truth-table
truthy-values
tutorials
add-new-properties-to-a-javascript-object
add-two-numbers-with-javascript
build-javascript-objects
comment-your-javascript-code
construct-javascript-objects-with-functions
create-a-javascript-slot-machine
create-decimal-numbers-with-javascript
debugging-javascript-with-browser-devtools
debugging-node-files-using-cli-commands
declare-javascript-objects-as-variables
declare-javascript-variables
index.md
decrement-a-number-with-javascript
delete-properties-from-a-javascript-object
detect-authentic-click-events
divide-one-number-by-another-with-javascript
finding-a-remainder-in-javascript
generate-random-fractions-with-javascript
generate-random-whole-numbers-with-javascript
get-current-url-in-javascript
give-your-javascript-slot-machine-some-stylish-images
how-to-create-a-countdown-timer
how-to-create-a-dropdown-menu-with-css-and-javascript
how-to-create-a-lightbox
how-to-create-a-slideshow
how-to-create-a-top-navigation-bar
how-to-create-an-accordion
how-to-create-popups
how-to-create-tabs
how-to-install-node-js-and-npm-on-windows
increment-a-number-with-javascript
invert-regular-expression-matches-with-javascript
iterate-with-javascript-for-loops
iterate-with-javascript-while-loops
javascript-for-loops-explained
page-redirects-using-javascript
perform-arithmetic-operations-on-decimals-with-javascript
store-multiple-values-in-one-variable-using-javascript-arrays
subtract-one-number-from-another-with-javascript
the-javascript-version-of-jquerygetjson
use-the-javascript-console
using-anonymous-functions-for-private-namespacing-in-your-javascript-apps
what-does-javascript-void-0-mean
write-reusable-javascript-with-functions
index.md
typeof
undefined-primitive-values
where-to
window-clearinterval-method
window-cleartimeout-method
window-confirm-method
window-localstorage
window-location
window-open-method
window-setinterval-method
window-settimeout-method
with
index.md
joomla
jquery
julia
kotlin
laravel
linux
logic
machine-learning
mathematics
meta
miscellaneous
mobile-app-development
mongodb
natural-language-processing
neovim
network-engineering
nginx
nodejs
php
product-design
progressive-web-apps
puppet
python
r
react
react-native
redux
rest-api
robotics
rt-os
ruby
rust
sass
security
semantic-ui
software-engineering
sql
ssh
svg
svn
swift
terminal-commandline
tomcat
tools
typescript
typography
user-experience-design
user-experience-research
vagrant
vim
virtualbox
visual-design
voice
vue
vue-cli
web-augmented-reality
web-components
web-performance
web-virtual-reality
wordpress
working-in-tech
xml
portuguese
russian
spanish
mock-guide
news
tools
.editorconfig
.eslintignore
.eslintrc
.gitattributes
.gitignore
.node-inspectorrc
.prettierrc
.snyk
.travis.yml
.vcmrc
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE.md
README(french).md
README.md
docker-compose-shared.yml
docker-compose.yml
lerna.json
netlify.toml
package-lock.json
package.json
sample.env
2018-10-16 21:32:40 +05:30

2.9 KiB

title
title
Declare Variables

Declare Variables

JavaScript variable declarations can be sorted into three distinct components: the variable type, the variable name, and the variable value.

    var myName = "Rafael";

Let's break the above line of code into the pieces that make it up:

    var/const/let

JavaScript variables can have three declaration types: var, const, and let. Var-type variables are global, if declared outside a function they can be accessed by any JS file (or the console), and if created within a function they are accessible regardless of block scope. Let-type variables are limited in scope to their block. See the example below for the difference.

     function varTest() {
      var x = 1;
      if (true) {
        var x = 2;  // same variable!
        console.log(x);  // 2
      }
      console.log(x);  // 2
    }

    function letTest() {
      let x = 1;
      if (true) {
        let x = 2;  // different variable
        console.log(x);  // 2
      }
      console.log(x);  // 1
    }

Const-type variables have the same scope as let variables (block scope), but are immutable. Whatever value a const-type variable is to be assigned, must happen when the variable is declared, and JavaScript will thrown an error if the variable is changed later.

    const genre = "non-fiction";
    console.log(genre); // "non-fiction";
    genre = "fantasy"; // error

Now that we can determine what the variable type is, let's take a look at the name. JavaScript variable names are written in camel case format. An example of camel case is: camelCase. In the context of our example:

    myName

The name is also we'll access the variable again later:

    console.log(myName); // "Rafael"

Finally, our value:

    "Rafael"

JavaScript is dynamically typed, which means any given variable can represent any given data type at any given time. For example:

    var example = "This is an example";
    example = [0, 1, 2, 3]
    example = {test: "Result"}
    example = 5

All those statements are perfectly valid - JavaScript variables can jump from string to array to object to integer.

Declare object as const

As mentioned above, const variable are immutable means value assigned to such variable at the time of declaration cannot be updated but there is a point to note in case object declaration with const. Object of type const also cannot be updated once defined but properties of object cab be. For example.

    const Car1 = {
        name: 'BMW',
        model: 'X1',
        color: 'black'
    }

Here, we cannot update the object but we can update the properties by accessing through dot(.) operator as below.

    Car1.color = 'Red';
    console.log(Car1);
    O/P - {name: "BMW", model: "X1", color: "Red"}

If we need to to make enitre object as immutable (including properties) then we have to use freeze method.