-1

I am using greeting variable inside function

function greet3() {
    greeting : 'HELLO GREET 3';
    this.greet = function () {
        console.log(greeting);
    };
}

this syntax does not give any error and also I am not able to fetch "greeting" in any case .I want to know what is happening here?

Shubham
  • 1,236
  • 6
  • 16
  • 1
    Declare/assign variables with `=`, not with `:`. (Also, preferably use a keyword like `const` first to avoid implicitly making it global.) – CertainPerformance Jun 13 '18 at 04:43
  • I know but I want to know that what happens when I do that , is js engine ignores this line completely? – Shubham Jun 13 '18 at 04:44
  • 1
    Possible duplicate of [Javascript strange syntax that works - but how?](https://stackoverflow.com/questions/39655737/javascript-strange-syntax-that-works-but-how) – Sebastian Simon Jun 13 '18 at 04:44
  • It's a label. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label – CertainPerformance Jun 13 '18 at 04:44
  • [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212), [MDN: Expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). – Sebastian Simon Jun 13 '18 at 04:45
  • You can also use tools like [JSHint](http://jshint.com/) which yields _“Label 'greeting' on HELLO GREET 3 statement.”_. – Sebastian Simon Jun 13 '18 at 04:49
  • 1
    simple solution ... don't use *strange syntax* :p – Jaromanda X Jun 13 '18 at 05:02

1 Answers1

1
  • first you have to use '=' instead of ':' for assign
  • second you must have to use this keyword for referring variable which allow to use variable in local scope or use var here is a code

    function greet3() {
        this.greeting = 'HELLO GREET 3';
        this.greet = function () {
            console.log(this.greeting);
        };
    }
    
    var g =  new greet3();
     g.greet();
    
manan5439
  • 808
  • 6
  • 23