Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use _ in variable names?

I have seen variables like _ image and was wondering what _ meant?

like image 867
SeriousTyro Avatar asked Aug 01 '11 19:08

SeriousTyro


People also ask

What does _ mean in variable?

The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use.

Can you use _ in variable names?

Variable names can never contain spaces. The underscore character ( _ ) can also appear in a name.

Should I use underscores in variable names?

Variable names should not start with underscore ( _ ) or dollar sign ( $ ) characters, even though both are allowed. This is in contrast to other coding conventions that state that underscores should be used to prefix all instance variables. Variable names should be short yet meaningful.

What does _ in front of variable mean?

Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable.


2 Answers

It doesn't mean anything. It is rather a common naming convention for private member variables to keep them separated from methods and public properties. For example:

class Foo {    private int _counter;     public int GetCounter()    {       return _counter;    }     public int SetCounter(int counter)    {       _counter = counter;    } } 
like image 200
Avada Kedavra Avatar answered Sep 20 '22 12:09

Avada Kedavra


In most languages _ is the only character allowed in variable names besides letters and numbers. Here are some common use cases:

  • Separating words: some_variable
  • Private variables start with underscores: _private
  • Adding at the end to distinguish from a built-in name: filter_ (since filter is a built-in function)
  • By itself as an unused variable during looping: [0 for _ in range(n)]

Note that some people really don't like that last use case.

like image 29
Andrew Clark Avatar answered Sep 22 '22 12:09

Andrew Clark