1

I const a variable in an if statement but I can't use the variable out of the statement

const a = 1

const b = 1

if (a == b) {
  const c = 1
  console.log(c)
}
console.log(c)

fist it gives me c ( in the if statement) then it gives me an error(out of the if statement)

Shubham Baranwal
  • 2,492
  • 3
  • 14
  • 26
Energieyy
  • 13
  • 1
  • 3
  • 6
    that's because [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) has blocked-scope, you can declare it as `var` or declare it outside the `if` initially using `let`, and then initialize it within the `if` – Nick Parsons Sep 05 '19 at 09:54
  • It's indeed block scoped. Meaning; it's not accessible outside of the `{ }`. If you want to do something inside the if statement you can use `let` outside the if and reassign the value in the condition statement – Facyo Kouch Sep 05 '19 at 09:56

4 Answers4

2

you could either declare it before with let and change its value later on:

const a = 1
const b = 1
let c;

if (a == b ){
    c = 1
}
console.log(c)

or write a function that returns a value based on the other const.

const a = 1
const b = 1
let c = myFunction();

function myFunction() {
  if (a == b ){
    return 1
  }
}
console.log(c)
Gabriele Magno
  • 196
  • 1
  • 13
0

In Javascript let, const uses block scoping + those are special types that does not get hoisted.
Here, you are trying to access 'c' which is not available in scope and you are getting error.

Durgesh
  • 205
  • 2
  • 9
0

if you are declaring c inside if condition it wont be accessible out of if and also you cannot make c as const ,because you have to assign a value when you declare a const variable and hence you cannot change again c inside 'if'

const a = 1
const b = 1
var c=1;
if (a == b ){
    c = 1
    console.log(c)    
}
console.log(c)
Nijin P J
  • 1,302
  • 1
  • 9
  • 15
0

It's just because It's scope, In this case, c is available into if block only If you want it outside then you need to declare c with let

const a = 1;

const b = 1
let c = null;

if (a === b) {
    c = 1;
    console.log(c);
}
   console.log(c);
Neel Rathod
  • 2,013
  • 12
  • 28