What does the `new` keyword do in JavaScript? Explain with examples
Hello everyone! I just started learning JavaScript and came across the `new` keyword. Honestly, I'm confused. I think I understand that it's related to creating objects, but how exactly it works is not entirely clear.\n\nFor example, I see this code:\n\n```javascript\nfunction Person(name) {\n this.name = name;\n this.sayHello = function() {\n console.log('Hello, my name is ' + this.name);\n };\n}\n\nconst user = new Person('Anna');\nuser.sayHello(); // Hello, my name is Anna\n```\n\nBut if I write without `new`:\n\n```javascript\nconst user = Person('Anna');\nconsole.log(user); // undefined\n```\n\nWhy does this happen? What exactly does `new` do internally? I've heard that it somehow binds `this`, but I don't understand the details.\n\nAlso, I've seen that in some textbooks they write constructor functions with
No answers yet.
Log in to leave an answer