How to create constant and a read-only property in JavaScript



In an interview, they often ask you about constant variables and how to create read-only properties in JavaScript. This video explains you that how constants and read-only property can be created in JavaScript.

**********
You can create a constant using the const keyword. The const has statement level scoping as the let keyword.

const foo = 9;

********************
To create a object’s property as read-only use Object.defineProperty. ‘

‘use strict’

var Dog = {

name : ‘tommy’
}

console.log(Dog.name);

Object.defineProperty(Dog,’name’,{writable:false})

Dog.name = “kommy”; // error
console.log(Dog.name);
**********************************

Teacher – Dhananjay Kumar , Microsoft MVP, Google GDE.
Blog : https://debugmode.net/
Email : debugmode@outlook.com (contact for training or consulting)

Please subscribe to the channel for all latest videos.

source

Reply

Do NOT follow this link or you will be banned from the site!